为什么我们需要使用awaitTermination而不是shutdownNow?

问题描述

我正在遵循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()awaitTerminationshutdownNow()的描述;

我了解
shutdown()仅停止提交新线程。

awaitTermination等待正在运行的线程被关闭。如果执行完成,超时或当前线程中断之一,则返回一个值。

shutdownNow()使用Thread.interrupt()中断线程。

我的问题是,如果我确定我的线程仅使用sleep,而Thread.interrupt()可能会中断我的线程。像Oracle推荐的那样,还有一个值可以调用awaitTermination吗?

我知道shutdownNow()可能有机会不关闭线程,但是为什么我们不能继续执行类似的操作来强制停止线程,然后查看是否还有未停止的线程呢? / p>

pool.shutdown();
pool.shutdownNow();
  try {
     if (!pool.awaitTermination(60,TimeUnit.SECONDS)) {
           System.err.println("Pool did not terminate");
     }
   } 

解决方法

“标准进程”只是试图优雅地处理关闭操作,前提是不要在不需要时中断线程。

首先,它停止接受新任务提交,并让正在进行的任务完成其工作。只有在宽限期内未完成操作时,它才会强制终止。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...