关于 Java's ExecutionService 的文档,有一个关闭执行程序服务的示例方法,如下所示:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
保留中断状态的目的是什么?
最佳答案
当您捕获 InterruptedException
时,当前线程上的中断标志将设置为 false。因此,您应该将其设置回 true,以便在该线程下执行的其他代码片段知道中断标志已设置,以防它们检查它。
大多数程序员可能不需要检查中断标志,我至少知道这在我们编写的企业代码中很少见。但对于库代码,最好在执行任何阻塞代码之前检查中断标志。否则,库代码可能会阻止线程(以及可能的应用程序)关闭。
因此,在捕获 InterruptedException 后,最好将中断标志设置回 true。
关于java - 为什么关闭 Java Executor 时要保留中断状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415437/