java为什么不支持线程。isInterrupted()即使在调用线程后也返回false。currentThread()。中断()
当我运行这个测试时,为什么sleepThread.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();
}
}
这是输出:
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
# 1 楼答案
这是因为当最后一句话到达的时候
线会死的
尝试删除主线程中的2秒睡眠,你会看到不同之处(尝试几次运行,它可能仍然打印为false,但至少主线程有机会看到另一个线程处于活动状态)
# 2 楼答案
尝试改变
到