我正在实现一个抛出 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/