不要吞下中断
有时,抛出InterruptedException并不是一种选择,例如Runnable定义的任务调用可中断方法时。在这种情况下,您不能抛出InterruptedException,但也不想执行任何操作。当阻塞方法检测到中断并引发InterruptedException时,它将清除中断状态。如果捕获了InterruptedException但无法将其抛出,则应保留发生中断的证据,以便调用堆栈中更高级别的代码可以了解该中断并在需要时对其进行响应。可以通过调用interrupt()来“重新中断”当前线程来完成此任务,如清单3所示。至少,每当您捕获InterruptedException并且不抛出该异常时,请在返回之前重新中断当前线程。
public class TaskRunner implements Runnable {
private BlockingQueue queue;
public TaskRunner(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
while (true) {
Task task = queue.take(10, TimeUnit.SECONDS);
task.execute();
}
}
catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
}