【发布时间】:2020-08-26 22:59:12
【问题描述】:
我正在遵循 oracle 推荐的标准流程来关闭执行程序服务。这是推荐的代码:
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();
}
}
我阅读了shutdown()、awaitTermination 和shutdownNow() 的描述;
我了解shutdown() 只会停止提交新线程。
awaitTermination 等待正在运行的线程被关闭。如果执行完成、超时或当前线程中断之一,则返回一个值。
shutdownNow() 使用Thread.interrupt() 来中断线程。
我的问题是,如果我确定我的线程只使用sleep,它可以被Thread.interrupt() 打断。像oracle推荐的那样调用awaitTermination还有价值吗?
我知道shutdownNow() 可能有机会不关闭线程,但为什么我们不能继续执行类似的操作来强制停止线程,然后查看是否还有未停止的线程?
pool.shutdown();
pool.shutdownNow();
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("Pool did not terminate");
}
}
【问题讨论】:
-
噢噢噢!!!!是的,你是对的,所以我的代码做的不仅仅是睡眠,它首先睡眠一段时间然后开始做其他事情。在这种情况下,当我的代码在做其他事情时,如果我不使用 awaitTermination,并且如果其他事情运行了很长时间,它不会立即终止,对吗?
标签: java thread-safety executorservice