最近,我读了《Java网络编程》,在第5.5节,第5.5.2.6部分,有以下代码:
public TimeSlicer(long milliseconds, int priority) {
this.timeslice = milliseconds;
this.setPriority(priority);
// If this is the last thread left, it should not
// stop the VM from exiting
this.setDaemon(true);
}
只是不太明白评论,守护线程与VM退出有什么关系?提前谢谢。
最佳答案
当没有任何非守护线程仍在运行时,Java VM 就会退出。通过使用 setDaemon(true)
将线程标记为守护线程,您可以告诉虚拟机即使该线程仍在运行,也可以退出。
来自java.lang.Thread
documentation :
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
关于java - 线程应该做什么才能不阻止虚拟机退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9509179/