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

标签 java multithreading concurrency

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

相关文章:

java - pom 文件 java tools.jar 问题

java - 在 Elasticsearch 中创建 TransportClient 时限制 ThreadPool 中的线程数

java - 如何启动/停止和监视java线程?

c++ - C 或 C++ Win32 如何获取程序中运行的线程数?

java - 如何原子地替换非同步并发列表或数组

javascript - 如果条件始终返回 false(省略号)

java - 如何输出代码正在运行的循环的哪一次迭代

java - 没有 pojo 的改造和 GSON

java加密大文件导致java.lang.OutOfMemoryError : Java heap space,可能的解决方案

无论我做什么,WCF 服务都只处理 10 个并发调用