2015-08-24 104 views
2

當我運行這個測試時,爲什麼sleepThread.isInterrupted()總是返回false?爲什麼在我調用Thread.currentThread()之後thread.isInterrupted()返回false中斷()

(我不得不執行Thread.currentThread().interrupt()設置中斷標誌時,趕上InterruptedException)。

@Test 
public void t() { 
    Thread sleepThread = new Thread() { 
     @Override 
     public void run() { 
      try { 
       Thread.sleep(5 * 1000); 
      } catch (InterruptedException e) { 
       System.out.println("have been interruptted...."); 
       e.printStackTrace(); 

       Thread.currentThread().interrupt(); 

       // in here this.isInterrupted() will return true 
       System.out.println("now , instant interrupt flag : " 
       + this.isInterrupted()); 
      } 
     } 
    }; 
    sleepThread.start(); 

    try { 
     sleepThread.interrupt(); 
     Thread.sleep(2 * 1000); 

     // in here ,why sleepThread.isInterrupted() return false ? 
     System.out.println("sleep thread interrupt flag : " 
     + sleepThread.isInterrupted()); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

這是輸出:因爲達到

System.out.println("sleep thread interrupt flag : " + sleepThread.isInterrupted()); 

線程的最後一條語句會死的時候

have been interruptted 
now , instant interrupt flag : true 
java.lang.InterruptedException: sleep interrupted 
    at java.lang.Thread.sleep(Native Method) 
    at com.roundwith.concurrent.Interrupt_Test$1.run(Interrupt_Test.java:15) 
sleep thread interrupt flag : false 
+0

這裏類似的問題沒有解決:[Thread.isInterrupted始終返回false](http://stackoverflow.com/questions/20677604/thread-isinterrupted-always-returns-false) –

+0

邊欄:這看起來像是一個不明智的方式來使用中斷。你以後有什麼樣的行爲,爲什麼你需要它? –

回答

0

它。

嘗試去除主線程中2秒鐘的睡眠並且您會看到不同(嘗試幾次運行 - 它可能仍會打印錯誤,但至少主線程有機會看到其他線程還活着)。

+0

你*可能*看到不同之處。仍然不能保證這裏的「主」線程在死亡之前有時間看到睡眠線程。 –

+0

@SnildDolkow當然。爲清晰起見進行編輯。 – manouti

0

嘗試改變,

Thread.sleep(2 * 1000); 

//Thread.sleep(2 * 1000); 
相關問題