为什么 JVM 不等待用户应用程序生成的守护线程?
“如果最后一个非守护线程完成,虚拟机就会终止。” 我的问题是,应用程序生成的守护线程会发生什么情况?为什么 JVM 不等待它们完成?
"The virtual machine terminates if the last non-daemon thread has finished."
My question is, What happens to the daemon threads spawned by the application? Why does the JVM not wait for them to finish?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
守护线程的全部目的是,如果它是唯一运行的线程,则它不会使 JVM 保持活动状态; 这是设计使然。您可能希望这样做的原因有很多。
例如,对于 Swing 应用程序,用户可能在后台守护线程(而不是在事件调度线程上)调用了长时间运行的任务。在任务完成之前,用户尝试退出应用程序。在这个阶段,应用程序开发人员可能已经决定最好立即关闭应用程序,而不是将关闭尝试延迟到长时间运行的计算完成,因此他们决定分配计算线程守护进程状态。
The whole purpose of a daemon thread is that it not not keep the JVM alive if it is the only thread running; this is by design. There are many reasons you might wish to do this.
For example, with a Swing application the user may have invoked a long running task on a background daemon thread (as opposed to on the Event Dispatch thread). Prior to the task completing the user attempts to exit the application. At this stage the application developer may have decided that it is better to shut down the application immediately rather than have the shut-down attempt delayed until the long running computation completes, hence why these decided to assign the computation thread daemon status.
因为它们是守护线程。这就是它的意思。没有别的意思。
Because they're daemon threads. That's what it means. It doesn't mean anything else.