2012-05-21 35 views
1

類DaemonThread繼承Thread {終於方法與嘗試在Java中

public void run() { 
    System.out.println("Entering run method"); 

    try { 
     System.out.println("In run Method: currentThread() is" 
      + Thread.currentThread()); 

     while (true) { 
      try { 
       Thread.sleep(500); 
      } catch (InterruptedException x) { 
       System.out.println("hi"); 
      } 

      // System.out.println("In run method: woke up again"); 

      finally { 
       System.out.println("Leaving run1 Method"); 
      } 
     } 
    } finally { 
     System.out.println("Leaving run Method"); 
    } 

} 

public static void main(String[] args) { 
    System.out.println("Entering main Method"); 

    DaemonThread t = new DaemonThread(); 
    t.setDaemon(true); 
    t.start(); 

    try { 
     Thread.sleep(900); 
    } catch (InterruptedException x) {} 

    System.out.println("Leaving main method"); 
} 

} 

爲什麼第二終於方法不能運行......我知道最後的方法必須具有運行任何條件在這種情況下..但只有第一個最後的方法,爲什麼不第二個終於跑。

+0

您如何期望退出'while循環以便第二個'finally'被執行? –

+0

第一個打印一個誤導消息。它根本不會離開run()方法,也不會離開while循環:它只是睡眠的結束。你迷惑自己。 – EJP

+0

良好的抓住@EJP,我甚至沒有看到打印消息。 –

回答

6

由於while(true)循環永遠不會結束println聲明!

如果您離開該循環,則會執行第二個finally塊。

0

您的代碼顯示您的while循環不會結束。因此,不存在到達外部區塊的問題。

只要使用任何其他條件,你可能會得到你想要達到的。 例如:

public void run() { 
    System.out.println("Entering run method"); 
    int flag = 1; 
    try { 
     System.out.println("In run Method: currentThread() is" 
      + Thread.currentThread()); 

     while (flag == 1) { 
      try { 
       Thread.sleep(500); 
       flag = 0; 
      } catch (InterruptedException x) { 
       System.out.println("hi"); 
      } 

      // System.out.println("In run method: woke up again"); 

      finally { 
       System.out.println("Leaving run1 Method"); 
      } 
     } 
    } finally { 
     System.out.println("Leaving run Method"); 
    } 

} 
0

它永遠不會執行finally塊作爲while循環總是TRUE.Also,從Java評論

"if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues." 
2

從理論上講它應該運行第二個最後的方法,但因爲它在沒有結束的while(true)循環之外,那麼它不能被訪問。

0

我想你會期望在JVM退出時因爲線程是守護進程,會自動退出循環。那是不正確的。守護進程線程簡單地死亡(在當前正在執行的代碼中的位置)