问题
谁能告诉我Java中的守护程序线程是什么?
#1 热门回答(532 赞)
守护程序线程是一个线程,它不会阻止JVM在程序完成但程序仍在运行时退出。守护程序线程的一个示例是垃圾收集。
你可以使用setDaemon(boolean)方法在线程启动之前更改Thread守护程序属性。
#2 热门回答(293 赞)
创建新线程时,它继承其父级的守护程序状态。
正常的线程和守护程序线程在退出时会发生什么不同。当JVM停止时,任何剩余的守护程序线程都被放弃:最后块不会被执行,堆栈也不会被解除 - JVM就会退出。由于这个原因,应该谨慎使用守护程序线程,并且将它们用于可能执行任何类型的I / O的任务是危险的。
#3 热门回答(150 赞)
以上所有答案都很好。这是一个简单的小代码片段,用于说明差异。尝试使用setDaemon中的每个true和false值。
public class DaemonTest {
public static void main(String[] args) {
new WorkerThread().start();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
// handle here exception
}
System.out.println("Main Thread ending") ;
}
}
class WorkerThread extends Thread {
public WorkerThread() {
// When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
setDaemon(true);
}
public void run() {
int count = 0;
while (true) {
System.out.println("Hello from Worker "+count++);
try {
sleep(5000);
} catch (InterruptedException e) {
// handle exception here
}
}
}
}