等待ExecutorService完成所有任务的最简单方法是什么?我的任务主要是计算,所以我只想运行大量的工作 - 每个核心一个.现在我的设置如下:
ExecutorService es = Executors.newFixedThreadPool(2);
for (DataTable singleTable : uniquePhrases) {
es.execute(new ComputeDTask(singleTable));
}
try{
es.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
ComputeDTask实现runnable.这似乎正确执行任务,但代码崩溃wait()了IllegalMonitorStateException.这很奇怪,因为我玩了一些玩具示例,它似乎工作.
uniquePhrases包含数万个元素.我应该使用其他方法吗?我正在寻找尽可能简单的东西
在我的webapp中,我创建了一个ExecutorService使用固定大小的ThreadPool的服务.我ExecutorService在整个应用程序生命周期中重复使用它.
private static ExecutorService pool = Executors.newFixedThreadPool(8);
Run Code Online (Sandbox Code Playgroud)
所有都在Tomcat中运行,它在向下发出错误时给出了以下错误:
appears to have started a thread named [pool-1-thread-1] but has failed to stop it. This is very likely to create a memory leak.
Run Code Online (Sandbox Code Playgroud)
我确实意识到我需要在关闭tomcat之前关闭ExecutorService.Soms SO线程已经谈到了这一点,但我找不到一个干净的方法来处理这个问题.
我是否应该ShutdownHook在线程和执行程序的正常关闭中使用@ Tim-bender ?或者我应该使用CachedThreadPool吗?