守護線程是一種比較特殊的線程,通常用於處理後臺的工做,它會隨着調用線程的結束而技術:java
看下面一段代碼服務器
package com.example.demo.threads; import java.util.concurrent.TimeUnit; /** * 守護線程 */ public class MainTest2 { public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(10); System.out.println(">>>>>執行了10秒的方法,線程name:" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.start(); //thread.setDaemon(true); try { TimeUnit.SECONDS.sleep(5); System.out.println(">>>>>執行了5秒的方法,線程name:" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }
執行這段程序以後就會發現,程序先打印主現成的的main方法,在打印thread-0的方法,在此期間jvm沒有關閉,一直等到執行完了Thread-0打印的方法時才退出。jvm
接下來在看下咱們代碼,設置一下thread爲守護線程ide
package com.example.demo.threads; import java.util.concurrent.TimeUnit; /** * 守護線程 */ public class MainTest2 { public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(10); System.out.println(">>>>>執行了10秒的方法,線程name:" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.setDaemon(true); thread.start(); try { TimeUnit.SECONDS.sleep(5); System.out.println(">>>>>執行了5秒的方法,線程name:" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }
執行的結果以下:它並無等到Thread線程執行完畢在結束,而是直接隨着main線程的結束而結束。spa
注意點:線程
1.設置線程爲守護線程很簡單,調用線程的setDaemon()方法設置成true便可,false爲正常線程code
2.線程是否爲守護線程和他的父線程有很大的關係,若是父線程爲正常線程,則子線程也是守護線程。反之,若是想要修改就能夠藉助 setDaemon()方法blog
3.線程的isDaemon方法能夠判斷線程是否爲守護線程。遊戲
4.setDaemon()的方法只有在線程啓動以前才能生效,若是一個線程已經死忙,那麼在設置setDaemon就會拋出 IllegalThreadStateException的異常。get
守護線程的做用:
1.守護線程的特色,當主線程結束的時候,其(主線程開啓的子線程)也跟着結束。
2.使用場景,jvm虛擬機中的垃圾回收線程。
3.好比有一個遊戲程序,其中有一個線程正在與服務器不斷的進行交互獲取玩家最新的金幣,武器等這些信息,若但願在退出遊戲客戶端的時候,這些數據同步的工做也能當即結束。
4.好比註冊中心(eruka)中與服務的心跳傳輸機制。