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

标签 java multithreading virtual-machine daemon

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

相关文章:

java - 如何为 Rhapsody 表生成自定义选择器?

java - Postgres JDBC : Especific error code of PSQLException?

Java Map ReplaceAll 与多个字符串匹配

java - 我在 java 中调用一个我无法控制的方法。如果我没有得到它的回应,我想杀死它并继续前进

python - 为什么 super(Thread, self).__init__() 不能用于 threading.Thread 子类?

java - 如何在分布式应用程序中管理 session

VMware 工作站 16 上的 Ubuntu 22.04 VM 卡住

azure - 使用 ARM 模板在 Azure VM 上安装应用程序或软件

java - 从 java keystore 获取证书详细信息

c++ - 线程创建 CPP