所謂的後臺線程,是指在程序運行的時候在後臺提供一種通用服務的線程,並且這種線程並不屬於程序中不可或缺的部分。因此當所有的非後臺線程結束時,程序也就終止了,同時會殺死所有後臺線程。反過來說,只要有任何非後臺線程(用戶線程)還在運行,程序就不會終止。後臺線程在不執行finally子句的情況下就會終止其run方法。後臺線程創建的子線程也是後臺線程。
import java.util.concurrent.TimeUnit;
/**
* 描述: 後臺守護線程示例
* 版權: Copyright (c) 2012
* 版本: 1.0
* 創建日期: 2012-7-3
* 創建時間: 上午09:57:27
*/
public class DaemonDemo implements Runnable{
public void run()
{
try{
while(true)
{
Thread.sleep(1000);
System.out.println("#"+Thread.currentThread().getName());
}
}catch(InterruptedException e)
{
e.printStackTrace();
}
finally{
System.out.println("finally!");
}
}
public static void main(String []args)
{
for(int i= 0;i<10;i++)
{
Thread deamon = new Thread(new DaemonDemo());
deamon.setDaemon(true);
deamon.start();
}
System.out.println("All deamon started!");
try{
TimeUnit.MICROSECONDS.sleep(1000*5000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Main exit!");
}
}
通過運行結果來看,子線程是受控於主線程的,子線程退出時,JVM強制終止了守護線程,但並非以異常方式結束的,連finally語句塊也不執行,這樣的話想要捕獲守護線程退出的狀態似乎增加了難度。