2011-04-19 72 views
0

主題setDeaemon根據Java時,setDaemon設置爲true迷惑,對Java中

它不妨礙JVM 當節目結束,但 線程仍在運行退出。一個守護進程線程的例子是 垃圾回收。

從下面的代碼示例,由主線程創建的線程停止時setDaemon設置爲執行,實際上它應該繼續運行。當setDaemon設置爲false即使主線程退出,我的子線程打印值。 請好好澄清我的疑問。

public class DeamonSample implements Runnable 
{ 
     public void run() 
     { 
      try 
{ 
System.out.println("T1 started..."); 

        for (int i=0;i<1000;i++) 
        { 
         TimeUnit.SECONDS.sleep(1); 
         System.out.print(i+" "); 
        } 
      } 
      catch (InterruptedException e) 
      { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
      } 
      finally 
      { 
        System.out.println("T1 ended..."); 
      } 

     } 


     /** 
     * @param args 
     */ 
     public static void main(String[] args) 
     { 
      // TODO Auto-generated method stub 
      System.out.println("Main Started..."); 
      System.out.println("Main Thread Type="+Thread.currentThread().isDaemon()); 
      DeamonSample deamonSample=new DeamonSample(); 
      Thread t1=new Thread(deamonSample); 
      t1.setDaemon(true); 
      t1.start(); 
      System.out.println("T1 Type="+t1.isDaemon()); 
      System.out.println("Main Thread Type="+Thread.currentThread().isDaemon()); 
      System.out.println("Main ended..."); 
     } 

} 

回答

3

默認情況下線程不是守護進程線程。如果你使用任何不是守護進程的線程結束主進程,那麼進程將繼續運行。通過調用setDaemon(true),你告訴JVM你的線程不應該在main結束時阻塞關閉。

1

當執行t1.setDaemon(true);時,DeamonSample實例肯定不會停止;你看到的不確定性來自印刷品。字符在被合併成單個流之前被寫入線程本地緩衝區。

這裏有一段代碼來說明。兩個線程輪流遞增一個計數器並打印其狀態,但是您看到的數字可能非常不合適。

import java.util.concurrent.atomic.AtomicInteger; 

public class FunnyPrinter extends Thread { 
    static AtomicInteger counter = new AtomicInteger(0); 

    int parity; 

    public FunnyPrinter(int parity) { 
     super(); 
     this.parity = parity; 
    } 

    public void run() { 
     for (;;) 
      if (counter.intValue() % 2 == parity) 
       System.out.println(counter.incrementAndGet()); 
    } 

    public static void main(String[] args) { 
     FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1); 
     t1.start(); t2.start(); 
    } 
} 

如果你需要決定,該塊年底前同步在System.outflush它。

0

主線程終止之前,如果你的新線程isDaemon您的守護線程可以打印出所有你的號碼... = TRUE,嘗試啓動線程()後,這條線:

... 
Thread t1=new Thread(deamonSample); 
try{ 
    t1.join(); 
}catch(InterruptedException ie){ 
    ie.printStackTrace(); 
} 
... 

你會看到,守護線程將走到盡頭......(至少,也不會轉回去是多線程的了,但是這例子是澄清的目的僅爲)

+0

它不應該是't1.join()'? – 2011-04-19 08:40:06

0

從下面的代碼示例,當setDaemon設置爲true時,由主線程創建的線程停止執行

這不會發生。再次檢查你的輸出。輸出將包含以下行:

主要入門...
主線程類型=假
T1類型=真
主線程類型=假
主要結束......

實際上它應該繼續運行。

作爲守護線程,它不會。由於所有非守護線程(main)都已完成,因此jvm將退出。

setDaemon設置爲false即使主線程退出時我的子線程打印值。請好好澄清我的疑問。

正確