我知道Deamon主持后台线程。 我们可以通过调用setDaemon(true)来创建我们自己的守护进程线程。
我的问题是:为什么和什么时候需要创建我们的线程作为守护进程线程?
I know that Deamon threads background threads. We can create our own daemon thread by calling setDaemon(true).
My question is: why and when do we need to create our thread as daemon thread?
最满意答案
当所有运行的线程都是守护进程线程时,JVM退出。 所以想象你正在写一个简单的游戏,你的主要方法循环,直到你决定退出。 并且想象一下,在游戏开始的时候,你会开始一个线程,不断地轮询一些网站来触发警报。 当您决定结束游戏时,您希望JVM退出。 你不希望无尽的轮询阻止游戏结束。 所以你使这个轮询线程成为一个守护进程线程。
The JVM exits when all the running threads are daemon threads. So imagine you're writing a simple game where your main method loops until you decide to quit. And imagine that at the start of the game, you start a thread that will endlessly poll some website to trigger alerts. You would like the JVM to exit when you decide to end the game. You don't want the endless polling to prevent the game from ending. So you make this polling thread a daemon thread.
更多推荐
发布评论