当我运行这个测试时,为什么
这是输出结果:
sleepThread.isInterrupted()
总是返回false?(在捕获InterruptedException
时,我必须执行Thread.currentThread().interrupt()
来设置中断标志。)@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();
}
}
这是输出结果:
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