守护程序线程何时有用? [英] When are daemon threads useful?

查看:85
本文介绍了守护程序线程何时有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道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.

这篇关于守护程序线程何时有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆