ExecutorService 中的 InterruptedException

6 java concurrency interrupted-exception

在捕获InterruptedException由 管理的任务内部时,我们应该设置中断标志ExecutorService吗?还是我们应该吞下InterruptedException

例子:

final ExecutorService service = ...;
final Object          object  = ...;

service.submit(() -> {
    try {
        while (!condition) {
            object.wait();
        }
    } catch (final InterruptedException exception) {
        Thread.currentThread().interrupt(); // yes or no?
    }
});
Run Code Online (Sandbox Code Playgroud)

eri*_*son 4

在提交给 的任务中ExecutorService,接收中断是取消任务执行的信号。因此,在您的代码示例中,答案是“否”,不要再次设置中断。

据我在源代码中看到的,重新断言中断状态将被忽略,但它确实浪费了执行器中的一些工作,因为InterruptedException如果工作线程尝试获取另一个任务,则会立即引发 an ,即然后根据执行器的状态确定为虚假并清除。

执行器是否及时关闭取决于任务响应中断而退出;它不依赖于恢复中断状态的任务。