檔案:ThreadDaemon1.java
public class ThreadDaemon1 {
public static void main(String[] args) {
Thread thread = new Thread(
new Runnable(){
public void run(){
while (true){
System.out.print("*");
}
}
}
);
thread.start();
}
}
在命令列視窗中,以 java ThreadDaemon1 驗證,執行結果
此時命令式窗不斷顯示 * 字元,而須以 Control + C 鍵強迫中止程式。
照道理,main()這個非 Daemon 的執行緒結束後,其所產生的 Daemon 執行緒 thread 也應該要結束才對,但,此時 thread 這個在背景執行的執行緒卻無法終止,問題在那裡?
問題在:若由非Daemon執行緒而產生的 Daemon 執行緒,此 Daemon 要以呼叫 setDaemon(true) 的方式,這樣非Daemon執行緒結束時,其所產生的 Daemon 執行緒也會跟著結束。
由 Daemon 執行緒所產生的執行緒,也屬於 Daemon 執行緒,所以也要用 setDaemon(true) 的方式設定。
public class ThreadDaemon1 {
public static void main(String[] args) {
Thread thread = new Thread(
new Runnable(){
public void run(){
while (true){
System.out.print("*");
}
}
}
);
thread.setDaemon(true);
thread.start();
}
}

沒有留言:
張貼留言