天天看點

将某一線程設定為背景線程

1、将線程設定為背景線程:與程式同生共死。比如垃圾回收器,長期運作,直到程式結束退出。

2、當線程不是背景線程時,主(服務線程)執行結束後,子線程沒執行完的還繼續執行直至運作結束。

3、當線程為背景線程時,主(服務線程)執行結束後,子線程沒有執行完的不在執行。

4、示範代碼如下:

package backthread;
/**
 * 将線程設定為背景線程:與程式同生共死。比如垃圾回收器,長期運作,直到程式結束退出
 * @author tiger
 * @Date 2017年7月25日--下午7:13:34
 */
public class BackThread {
  public static void main(String[] args) throws InterruptedException {
    MyThread th = new MyThread();
    //判斷是否為背景線程
    System.out.println("設定前 :是否為背景線程:"+th.isDaemon());
    //setDaemon(true) -- 設定為背景線程
//    th.setDaemon(true);
    System.out.println("設定後 :是否為背景線程:"+th.isDaemon());
    th.start();
    for (int i = 1; i <=10; i++) {
      System.out.println("主---"+i);
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("主線程死亡...");
  }
}
/**
 * 子線程類
 * @author tiger
 * @Date 2017年7月25日--下午4:41:32
 */
class MyThread extends Thread{
  @Override
  public void run() {
    for (int i = 1; i <=10; i++) {
      System.out.println("子--"+i);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("子線程死亡...");
  }
}      

5、不是背景線程時的運作結果: