参见英文答案 > How to properly shutdown java ExecutorService 2个
这是正在运行的代码,但我明确指定了等待时间.当所有线程都完成执行时,有没有办法退出ExecutorService.
ExecutorService es = Executors.newCachedThreadPool();
{
for(final List list:partitions){
es.execute(new Runnable() {
public void run() {
try{
System.out.println(list);
new CallAPI().make_call(list, access_token);
}catch(Exception e){
System.out.println(e);
}
}
});
Thread.sleep(5000);
}
boolean finshed = es.awaitTermination(15, TimeUnit.MINUTES);
es.shutdown();
boolean finshed = es.awaitTermination(15,TimeUnit.MINUTES); ==>我在这里等待时间,但我不想这样,因为我不知道线程什么时候会完成执行
解决方法:
听起来你想要ExecutorService.invokeAll.你所要做的就是将你的列表集合转换为Callables集合.
List> tasks = partitions.stream()
.map(list->{
System.out.println(list);
new CallAPI().make_call(list, access_token);
return "finished";
}).collect(Collectors.toList());
List> futures = es.invokeAll(tasks);
es.shutdown();
然后你有未来,你可以使用它们来检查异常,或者任务是否完成.
标签:java,multithreading,executorservice,executor
来源: https://codeday.me/bug/20190627/1306787.html