在Java的線程機制中,有兩類線程: this
Daemon Thread的做用是爲其餘線程的運行提供服務,好比說GC線程。其實User Thread線程和Daemon Thread守護線程本質上來講去沒啥區別的,惟一的區別之處就在虛擬機的離開時候:若是User Thread所有撤離,那麼Daemon Thread也就沒啥線程好服務的了,因此虛擬機也就退出了。只要當前JVM實例中尚存在任何一個非守護線程沒有結束,守護線程就所有工做;只有當最後一個非守護線程結束時,守護線程隨着JVM一同結束工做。守護線程最典型的應用就是 GC (垃圾回收器)。線程
守護線程並不是只有虛擬機內部能夠提供,用戶也能夠自行的設定守護線程,能夠經過Thread的setDaemon方法來設置,這個值的默認值是false,即默認是用戶線程code
class TestRunnable implements Runnable{ public void run(){ try{ Thread.sleep(1000);//守護線程阻塞1秒後運行 System.out.println("this thread is running"); catch(IOException e){ e.printStackTrace(); } } } public class TestDemo{ public static void main(String[] args) throws InterruptedException { Runnable tr=new TestRunnable(); Thread thread=new Thread(tr); thread.setDaemon(true); //設置守護線程 thread.start(); //開始執行分進程 System.out.println("main thread is finished"); } }
運行結果:只輸出了「main thread is finished」 由於設置了thread.setDaemon(true); 當沒有正在執行的用戶線程的時候,守護線程也會結束。進程
若是把thread.setDaemon(true); 註釋掉,會同時輸出:"main thread is finished"和"this thread is running"虛擬機