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的事情)