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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7142665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:49:46  来源:igfitidea点击:

Why does Thread.isInterrupted () always return false?

javamultithreadingconcurrency

提问by u290629

I found the method of JavaDoc:

我找到了JavaDoc的方法:

Returns: true if this thread has been interrupted; false otherwise.

返回: 如果此线程已被中断,则为真;否则为假。

I think something wrong with my understanding of the method. Further, I may misunderstand the concept ‘interrupt' in Thread.

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

Any explanation is welcome! Thank you!

欢迎任何解释!谢谢!

Code snippet:

代码片段:

In thread definition:

在线程定义中:

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

invoke:

调用:

theThread.interrupt();

采纳答案by cdhowie

Once the exception is thrown, the thread is no longer in an interrupted state.

一旦抛出异常,线程就不再处于中断状态。

回答by Stephen C

This behaviour is typicallydocumented in methods that throw that exception. For example, the javadoc for Object.wait()says:

此行为通常记录在引发该异常的方法中。例如,javadoc forObject.wait()说:

"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."

" InterruptedException- 如果在当前线程等待通知之前或期间任何线程中断了当前线程。当抛出此异常时,当前线程的中断状态将被清除。"

Indeed, the javadoc for the exception itself says this:

事实上,异常本身的 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();

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

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

Note how they emphasizethat the flag shouldbe cleared before the exception is thrown.

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



Why was it designed to work like this? You'd have to ask the designers, but I expect they figured that an exception handler should handlethe situation, and that there should therefore be no need for the flag to still be set at that point. (If the handler doesn't fully handle the situation it can either rethrow the exception, or call Thread.getCurrentThread.interrupt()to set the flag again.)

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

回答by Bohemian

Adding to cdhowie's answer, one standard pattern is to let the Thread handle interruption. This is useful with Executors, when the running code doesn't "own" the Thread and should not get in the way of interruption (unless you really know what you're doing)

添加到 cdhowie 的答案中,一种标准模式是让 Thread 处理中断。这对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(); // 
    }
}

回答by Sarel Botha

You would check isInterrupted() in your own code, for example from a loop. If the thread has been interrupted you can then throw InterruptedException to stop executing.

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

In your example if you caught InterruptedException you can be sure that it was interrupted and you don't have to check that method.

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