为什么Thread.isInterrupted()总是返回false?

我找到了JavaDoc的方法:

返回:如果此线程已被中断,则返回true; 否则是假的。

我认为我对该方法的理解有些不对劲。 此外,我可能会误解Thread中的“中断”概念。

欢迎任何解释! 谢谢!

代码段:

在线程定义中:

public void run() { try { //Do something } catch (InterruptedException e) { System.out.println(isInterrupted());//Always false return; } } 

引用:

 theThread.interrupt(); 

抛出exception后,线程不再处于中断状态。

此行为通常记录在抛出该exception的方法中。 例如, Object.wait()的javadoc说:

InterruptedException – 如果任何线程在当前线程等待通知之前或当前线程中断当前线程。当抛出此exception时,将清除当前线程的中断状态。

实际上,exception的javadoc本身就是这样说的:

“偶尔一个方法可能希望测试当前线程是否已被中断,如果是,则立即抛出此exception。以下代码可用于实现此效果:

 if (Thread.interrupted()) // Clears interrupted status! throw new InterruptedException(); 

请注意他们如何强调在抛出exception之前应该清除该标志。


它为什么设计成这样工作? 您必须询问设计人员,但我希望他们认为exception处理程序应该处理这种情况,因此应该不需要在该点设置该标志。 (如果处理程序没有完全处理这种情况,它可以重新抛出exception,或者调用Thread.getCurrentThread.interrupt()再次设置标志。)

添加到cdhowie的答案,一个标准模式是让线程处理中断。 当运行代码没有“拥有”线程并且不应该妨碍中断时(除非你真的知道你在做什么)这对Executors很有用。

 public void run() { try { //Do something } catch (InterruptedException e) { // Do whatever local clean up you need to ... // Then let the owning Thread know it's been interrupted, so it too can clean up Thread.currentThread().interrupt(); // } } 

您可以在自己的代码中检查isInterrupted(),例如从循环中检查。 如果线程已被中断,则可以抛出InterruptedException以停止执行。

在您的示例中,如果您捕获到InterruptedException,您可以确定它已被中断,您不必检查该方法。