當我運行這個測試時,爲什麼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
這裏類似的問題沒有解決:[Thread.isInterrupted始終返回false](http://stackoverflow.com/questions/20677604/thread-isinterrupted-always-returns-false) –
邊欄:這看起來像是一個不明智的方式來使用中斷。你以後有什麼樣的行爲,爲什麼你需要它? –