从ExecutorService的 Oracle API文档页面推荐的方法: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();
}
如果您的池有更多时间关闭,您可以更改1f (!pool.awaitTermination(60, TimeUnit.SECONDS))
至while (!pool.awaitTermination(60, TimeUnit.SECONDS))
关闭相关方法的简要概述启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。阻止所有任务在关闭请求之后完成执行,或者发生超时,或者当前线程被中断,以先发生者为准。