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

fge*_*fge 5 java exception-handling interrupted-exception

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

语境:

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

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

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

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

JB *_*zet 5

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

让我引用一下Java 并发实践

恢复中断。有时您不能抛出 InterruptedException,例如当您的代码是 Runnable 的一部分时。在这些情况下,您必须捕获 InterruptedException 并通过在当前线程上调用中断来恢复中断状态,以便调用堆栈上方的代码可以看到发出了中断,如清单 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();
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)