当我运行这个测试时,为什么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) –
边栏:这看起来像是一个不明智的方式来使用中断。你以后有什么样的行为,为什么你需要它? –