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

标签 java multithreading concurrency

我找到了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/

相关文章:

java - 如何使用 Java 从链接列表中的文本文件读取字符串?

java使用synchronized关键字的等待通知方法

java - 如何在java中的线程之间传递整数/其他变量?

ios - iOS 设置图像的并发

javascript - 通过全局变量 react 互斥体

java - 将 HashSet 与用户类 Employee 一起使用

java - 在 SDCard 上写入问题 - Android

java - 如何在 HashMap 中找到关于该元素的给定条件为真的任何元素

android - 从 AsyncTask 更新 UI 并正确处理屏幕旋转

c# - 互斥存储过程