我找到了JavaDoc的方法:
返回: true 如果该线程已被中断;否则为 false。
我觉得我对这个方法的理解有问题。此外,我可能误解了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/61335756/