所有线程完成执行后如何退出ExecutorService?

时间:2017-07-12 04:17:21

标签: java multithreading executorservice executor

这是正在运行的代码,但我明确指定了等待时间。当所有线程都已完成执行时,有没有办法退出ExecutorService

    ExecutorService es = Executors.newCachedThreadPool();
    {
      for(final List<String> 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); ==&gt;我在这里等待时间,但我不想要这个,因为我不知道线程什么时候会完成执行

4 个答案:

答案 0 :(得分:2)

  • 使用Future<?> f = executor.submit(new Runnable(...));
  • 将期货存储在列表中
  • 循环后,迭代期货并致电f.get()

这将阻止所有任务执行完毕。

然后,您可以拨打executor.shutdown()

答案 1 :(得分:2)

听起来你想要ExecutorService.invokeAll。您所要做的就是将您的列表集合转换为Callables集合。

List<Callable<String>> tasks = partitions.stream()
    .map(list->{
         System.out.println(list);
         new CallAPI().make_call(list, access_token);
         return "finished";   
    }).collect(Collectors.toList());

List<Future<String>> futures = es.invokeAll(tasks);
es.shutdown();

然后你有未来,你可以使用它们检查异常,或者任务是否完成。

答案 2 :(得分:0)

以下方法分两个阶段关闭ExecutorService,首先调用shutdown来拒绝传入的任务,然后在必要时调用shutdownNow来取消任何延迟的任务:

 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();
   }
 }

boolean awaitTermination(long timeout,TimeUnit unit) 阻止所有任务在关闭请求之后完成执行,或发生超时,或者当前线程被中断,以先发生者为准。

答案 3 :(得分:0)

要在完成所有任务后终止ExecutorService,只需调用es.shutdown()即可。您自己的线程将继续执行,而任务线程将处理所有排队的任务。

来自Java Doc:

  

关闭   启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。如果已经关闭,调用没有其他影响。   此方法不会等待先前提交的任务完成执行。使用awaitTermination来做到这一点。

当你想阻止你自己的线程时,你需要awaitTermination

相关问题