Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 中 User Thread 與 Daemon Thread 的差別

Java 把執行緒分成 User 執行緒與 Daemon 執行緒兩類,後者通常用來為前者提供服務。程式的 main() 方法所屬的執行緒就是一個 User 執行緒,而由 User 執行緒所創建的通常也是 User 執行緒。關鍵規則是:唯有當所有 User 執行緒都結束後,JVM 才會跟著關閉。

若在執行緒物件上呼叫 setDaemon(true),就能把它明確設為 Daemon 執行緒。時鐘處理、idle、垃圾回收、畫面更新等執行緒都屬於這類。新建立的執行緒預設會從建立它的執行緒繼承 daemon 狀態,除非你明確呼叫 setDaemon 加以改變。

要特別注意的是,setDaemon() 必須在呼叫 start() 之前設定。一旦執行緒已經啟動,它的 daemon 狀態便無法再更改;而 isDaemon() 則可用來查詢某執行緒是否為 Daemon。

下面的程式碼能清楚說明 daemon 的作用:當把執行緒 t 設為 Daemon 時,只要 User 執行緒(main)一結束,程式立刻退出,t 根本沒機會從 10 數到 1;但若把 t 設成非 daemon 的 User 執行緒,它就能安穩地把工作做完。

  1. import static java.util.concurrent.TimeUnit.*;  
  2. public class DaemonTest {  
  3.     public static void main(String[] args) throws InterruptedException {  
  4.         Runnable r = new Runnable() {  
  5.             public void run() {  
  6.                 for (int time = 10; time > 0; --time) {  
  7.                     System.out.println("Time #" + time);  
  8.                     try {  
  9.                         SECONDS.sleep(2);  
  10.                     } catch (InterruptedException e) {  
  11.                         e.printStackTrace();  
  12.                     }  
  13.                 }  
  14.             }  
  15.         };  
  16.   
  17.         Thread t = new Thread(r);  
  18.         t.setDaemon(true); // try to set this to "false" and see what happens   
  19.         t.start();  
  20.   
  21.         System.out.println("Main thread waiting...");  
  22.         SECONDS.sleep(6);  
  23.         System.out.println("Main thread exited.");  
  24.     }  
  25. }  

t 為 Daemon 執行緒時的輸出:

Time #10 / Time #9 / Time #8 / Main thread exited. / Time #7

t 為 User 執行緒時的輸出:

Main thread waiting... / Time #10 / Time #9 / Time #8 / Main thread exited. / Time #7 / Time #6 / Time #5 / Time #4 / Time #3 / Time #2 / Time #1

Copyright © Linux教程網 All Rights Reserved