我找到了JavaDoc的方法:
返回: 如果此线程已被中断,则为 true;否则为假。
我认为我对方法的理解有问题。此外,我可能会误解 Thread 中的“中断”概念。
欢迎任何解释!谢谢!
代码片段:
在线程定义中:
public void run() {
try {
//Do something
} catch (InterruptedException e) {
System.out.println(isInterrupted());//Always false
return;
}
}
调用:
theThread.interrupt();
最佳答案
此行为通常记录在引发该异常的方法中。例如,Object.wait()
的 javadoc 说:
"
InterruptedException
- if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
确实,异常本身的 javadoc 是这样说的:
"Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted()) // Clears interrupted status! throw new InterruptedException();
注意他们如何强调标志应该在抛出异常之前被清除。
为什么设计成这样工作?您必须询问设计人员,但我希望他们认为异常处理程序应该处理这种情况,因此此时不需要设置标志。 (如果处理程序没有完全处理这种情况,它可以重新抛出异常,或调用 Thread.getCurrentThread.interrupt()
再次设置标志。)
关于java - 为什么Thread.isInterrupted()总是返回false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7142665/