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) {} } } }
守护线程应用示例:java garbage collection。当没有线程运行时,不会产生垃圾,garbage collection也就没有发挥作用,JVM可以关闭。
守护线程应用背景:后台线程(比如可以收集某些系统状态的线程,发送email的线程,等不希望影响JVM的事情)
原文:http://blog.csdn.net/aaashen/article/details/45227363