守護線程是為其他線程提供服務的後台線程。JVM 的垃圾回收、內存管理、Finalizer 等都是典型守護線程。關鍵特性:
start() 前調用 setDaemon(true),否則拋出 IllegalThreadStateExceptionpublic final void setDaemon(boolean on)
```
參數:on - true 標記為守護線程
拋出:
- IllegalThreadStateException:線程已啟動
- SecurityException:無權限修改線程
```
/**
* Java線程:線程的調度-守護線程
* @author leizhimin
*/
public class Test {
public static void main(String[] args) {
Thread t1 = new MyCommon(); // 用戶線程
Thread t2 = new Thread(new MyDaemon());
t2.setDaemon(true); // 設置為守護線程
t2.start();
t1.start();
}
}
class MyCommon extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("線程1第" + i + "次執行!");
try { Thread.sleep(7); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
class MyDaemon implements Runnable {
public void run() {
for (long i = 0; i < 9999999L; i++) {
System.out.println("後台線程第" + i + "次執行!");
try { Thread.sleep(7); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
後台線程第0次執行!
線程1第0次執行!
線程1第1次執行!
後台線程第1次執行!
後台線程第2次執行!
線程1第2次執行!
線程1第3次執行!
後台線程第3次執行!
線程1第4次執行!
後台線程第4次執行!
後台線程第5次執行!
後台線程第6次執行!
後台線程第7次執行!
Process finished with exit code 0
明顯可見:
Runtime.addShutdownHook() 而非守護線程