public class DaemonTest {
public static void main(String[] args) {
new WorkerThread().start();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {}
System.out.println("Main Thread ending") ;
}
}
class WorkerThread extends Thread {
public WorkerThread() {
setDaemon(true) ; // 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.
}
public void run() {
int count=0 ;
while (true) {
System.out.println("Hello from Worker "+count++) ;
try {
sleep(5000);
} catch (InterruptedException e) {}
}
}
}
简单理解:守护进程是不会阻止JVM的关闭的。当有用户线程运行时,JVM不能关闭。当没有用户线程运行时,有没有守护线程没关系,JVM都会关闭。
守护线程应用示例:java garbage collection。当没有线程运行时,不会产生垃圾,garbage collection也就没有发挥作用,JVM可以关闭。
守护线程应用背景:后台线程(比如可以收集某些系统状态的线程,发送email的线程,等不希望影响JVM的事情)