gpt4 book ai didi

java - 线程应该做什么才能不阻止虚拟机退出?

转载 作者:行者123 更新时间:2023-12-02 07:56:49 24 4
gpt4 key购买 nike

最近,我读了《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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com