java - 我应该在抛出异常之前使用 Thread.currentThread.interrupt() 吗?

标签 java exception-handling interrupted-exception

我正在实现一个抛出 IOException 的接口(interface)。在我的实现中,我调用了另一个可以阻塞的方法,因此抛出 InterruptedException

上下文:

  • 如果我被打断,我想结束治疗;
  • 这不是我自己创建的话题。

我目前的想法是这样做(骨架代码):

@Override
public void implementedMethod()
    throws IOException
{
    try {
        methodThatBlocks();
    } catch (InterruptedException ignored) {
        Thread.currentThread().interrupt();
        throw new IOException();
    }
}

这是正确的方法吗?或者我应该只是 throw 而不是 .interrupt()

最佳答案

是的,你应该调用interrupt()让调用代码知道线程已经被中断了。如果您不这样做,因为 InterruptedException 会清除它,调用代码将无法知道中断并且不会停止运行,尽管它应该停止运行。

让我引用 Java 并发实践:

Restore the interrupt. Sometimes you cannot throw InterruptedException, for instance when your code is part of a Runnable. In these situations, you must catch InterruptedException and restore the interrupted status by calling interrupt on the current thread, so that code higher up the call stack can see that an interrupt was issued, as demonstrated in Listing 5.10.

public class TaskRunnable implements Runnable {
    BlockingQueue<Task> queue;
    ...
    public void run() {
        try {
            processTask(queue.take());
        } catch (InterruptedException e) {
             // restore interrupted status
             Thread.currentThread().interrupt();
        } 
    }
}

关于java - 我应该在抛出异常之前使用 Thread.currentThread.interrupt() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22620271/

相关文章:

java - JUnit 和 InterruptedException

java - 线程通过调用interrupt()被中断,但是Thread.isInterrupted()返回false

java - 取消文件打开对话框后出现 InterruptedException - 1.6.0_26

java - Elasticsearch 6.4 : XContentBuilder fails to close when passed to request. 映射()

php - 在每个 Controller 中处理相同的 try catch 结构

java - 在 Clojure 中强制垃圾收集是个好主意吗?

jsf - 从 ADF Faces JSF 1.2 中的托管 bean 构造函数导航

c# - 我可以执行多个 Catch block 吗?

java - 通过 jakson Java 使用嵌套多态对象进行反序列化

java - 为什么我的 java 程序会跳过 if 语句?