我面临着奇怪的行为。所有来源都告诉您在捕获中断异常后恢复中断标志后需要调用Thread.currentThread()。interrupt()。但我尝试创建一个简单的应用程序,在进程中断后检查中断状态
public class Main {
public static void main(String[] args) throws InterruptedException {
Runnable r = () -> {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
System.out.println("interrupted exception is occurred");
Thread.currentThread().interrupt();
System.out.println("interrupt flag is updated:" + Thread.currentThread().isInterrupted());
}
};
Thread thread = new Thread(r);
thread.start();
thread.interrupt();
boolean interruptFlag;
do {
Thread.sleep(1000);
interruptFlag = thread.isInterrupted();
System.out.println("interrupt flag:" + interruptFlag + " isAlive:" + thread.isAlive());
} while (!interruptFlag);
}
}
如果你尝试运行它,那么你得到
interrupted exception is occurred
interrupt flag is updated:true
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
它将无限运作。问题是为什么在线程死后iterrupt标志是错误的?
答案 0 :(得分:1)
当您从主线程检查中断状态时,第二个线程已经死亡,因此返回false。尝试将Thread.sleep(1000)置于等待循环的末尾,您将在中断状态下看到true。
此行为未记录,因此很难说它是缺少文档还是现有实现的功能。私有原生布尔值的实现是inInterrupted(boolean ClearInterrupted);方法需要检查多说。
类似的讨论:Thread.isInterrupted() returns false after thread has been terminated