本節摘要:介紹守護線程,代碼示例
一、守護線程
thread 類中有一個isDaemon的布爾變量,如果isDaemon=true代表該線程為守護線程,否則為用戶線程
1.1 守護線程特點
- 當所有用戶線程結束時,程序會終止,同時殺死進程中的所有守護線程
- 守護線程一般在后臺執行任務
- 守護線程創建的線程被自動設置為守護線程
二、守護線程示例
2.1 示例1
public class DaemonThreadDemo implements Runnable {
@Override
public void run() {
try {
while (true) {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread().getName() + "**Daemon:" + Thread.currentThread().isDaemon());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new DaemonThreadDemo(), "thread" + i);
t.setDaemon(true);//daemon值要在線程啟動之前設置
t.start();
}
System.out.println("all daemon thread start");
TimeUnit.MILLISECONDS.sleep(150);
}
}
輸出結果:
all daemon thread start
thread1**Daemon:true
thread0**Daemon:true
thread4**Daemon:true
thread6**Daemon:true
thread2**Daemon:true
thread3**Daemon:true
thread5**Daemon:true
thread7**Daemon:true
thread8**Daemon:true
thread9**Daemon:true
2.1.1、結果說明
創建了10個后臺線程,每個后臺線程都是死循環,但是主線程main在啟動后休眠了150毫秒后終止,因為已經沒有用戶線程運行,只剩守護線程。調整主線程的休眠時間,例如修改為50毫秒,會發現只打印 all daemon thread start
2.2 示例2
public class DaemonThreadDemo2 implements Runnable {
private int num = 0;
public void run() {
while (true) {
Thread t = new Thread("thread" + num++);
System.out.println(t.getName() + ":" + t.isDaemon());
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new DaemonThreadDemo2(), "I am a daemon thread");
t.setDaemon(true);//daemon值要在線程啟動之前設置
t.start();
TimeUnit.MILLISECONDS.sleep(50);
}
}
輸出結果:
thread0:true
thread1:true
thread2:true
thread3:true
thread4:true
thread5:true
.......
thread1031:true
thread1032:true
thread1033:true
thread1034:true
thread1035:true
2.2.1 結果說明:
所有由守護線程t創建的線程都是守護線程
三、總結
- 當沒有非守護線程時,程序立即退出
- 由守護線程創建的線程,默認也都是守護線程
轉載請注明作者及出處,并附上鏈接http://www.lxweimin.com/u/ada8c4ee308b