java - 来自 executorService 接口的 ShutdownNow 没有关闭进程中的任务
问题描述
在第一个进程从 invokeAny 方法提供一些输出后,我使用 shutdownNow 立即关闭进程。但是在输出中,即使在调用shutDownNow() 之后,我也可以看到,进程正在完成并完成它们的工作,然后才关闭。代码:
int numberOfRecordsInsertedSuccessfully = 0;
List<String> userRecordList = readFile(
"C:\\Users\\sonar\\git\\MultiThreading-Cocurrency\\JavaSEConcurrencyAPIStudyProject\\src\\main\\java\\Resources\\ExecutorServiceUserFile.txt");
// ExecutorService executorService = Executors.newSingleThreadExecutor(); //Thread pool of single thread.
// ExecutorService executorService = Executors.newFixedThreadPool(3); //Thread pool size is 3 here
ExecutorService executorService = Executors.newCachedThreadPool();
UserDao userDao = new UserDao();
List<Callable<Integer>> listOfCallable= new ArrayList<>();
userRecordList.forEach(x -> listOfCallable.add(new UserProcessor(x, userDao)));
try {
Integer future = executorService.invokeAny(listOfCallable);
System.out.println(future);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println(executorService.shutdownNow());
System.out.println("ExecutorService is shutting down " + executorService.isShutdown()); //After getting first future result this statement will be executed.
System.out.println("ExecutorService is Terminated " + executorService.isTerminated());
有关代码的更多详细信息,请参阅上面的 git 链接
类:ExecutorServiceThreeTypesOfShutDownMethodMainClass
包:com.Concurrency.JavaSEConcurrencyAPIStudyProject.HighLevelApis.ExecutorServiceInterface
使用项目:JavaSEConcurrencyAPIStudyProject
git 链接:项目的 Git 链接以获取更多详细信息
请帮忙,为什么会这样?我该如何解决这个问题?
解决方案
该方法的 Javadoc 说明如下:
除了尽最大努力停止处理正在执行的任务之外,没有任何保证。例如,典型的实现将通过 Thread.interrupt() 取消,因此任何未能响应中断的任务可能永远不会终止。
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html
因此,如果您的任务不检查中断标志并捕获并忽略,InterruptedException
那么shutdownNow()
将无法阻止它们
推荐阅读
- maven - 如何使用 github 中的“Reusing Workflows”功能?
- c# - 无法使用 Azure.Storage.Blobs NuGet 包将文件上传到 Azure Blob 存储
- java - 查找最近的点 - Java
- mql4 - MQL5 从函数返回并获取结构结果
- python - 如何链接 Sphinx 表中的函数?
- python - ModuleNotFoundError:没有名为“jmetal”的模块
- reactjs - Firebase 存储安全错误 - 错误地标记为网络钓鱼
- python - 如何修复 FileNotFoundError:[Errno 2] 没有这样的文件或目录:没有
- python - psycopg2从python字符串传递时间戳
- javascript - Google Apps 脚本(网络部署)自动重新加载页面