【问题标题】:how to check if all threads in executor service is done如何检查执行程序服务中的所有线程是否已完成
【发布时间】:2016-08-10 23:25:43
【问题描述】:

我正在尝试计算一些指标,一旦 myclass 中的所有线程都完成,一旦我达到超时场景,线程的工作就完成了,我可以为每个线程命中。现在在 Group 类的 main() 方法中,我如何等待所有 myclass 线程完成?

我不想使用任何 sleep() 场景

Group Class

  class myGroup {

  public void run(int numThreads) {
      executor = Executors.newFixedThreadPool(numThreads);
      executor.submit(new myclass(threadNumber));

  }

  public static void main(String[] args) {

       run(noOfthreads);

       // Collect metrics once all the myclass threads are done.
   }

 }

我的班级

  class myclass implements Runnable {

     try{
     }
     catch(SomeTimeoutException cte){

      // Job Done for thread
     }


  }

【问题讨论】:

  • 你可能想看看java.util.concurrent.CountDownLatch

标签: java multithreading threadpool executorservice


【解决方案1】:

可以这样做:

List<myclass> tasks = makeAListOfMyClassTasks();
// this will kick off all your tasks at once:
List<Future<myclass>> futures = executor.invokeAll(tasks);
// this will wait until all your tasks are done, dead, or the specified time has passed
executor.awaitTermination(10, TimeUnit.MINUTES); // change this to your liking

// check each Future to see what the status of a specific task is and do something with it
for (Future<myclass> future : futures) {
    if (future.isCancelled()) {
        // do something
    } else if (future.isDone()) {
        myclass task = future.get(); // this will block if it's not done yet
        task.whatever();
    }
}

@beatngu13 还指出了这个漂亮的类 ExecutorCompletionService;所以你可以这样做:

List<myclass> tasks = makeAListOfMyClassTasks();
CompletionService<Result> ecs = new ExecutorCompletionService<Result>(exectuor);
for (myclass t : tasks) {
    // this kicks off the task and returns a Future, which you could gather
    ecs.submit(t);
}
for (int i = 0; i < tasks.length(); i ++) {
    myclass task = ecs.take().get(); // this will block until the next task is done/dead
    // ... do something with task
}

期货信息: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html

这里有 ExecutorService 的例子: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

这个相关线程非常相关:ExecutorService, how to wait for all tasks to finish

希望这会有所帮助。

【讨论】:

  • 如果你添加ExecutorCompletionService,我会+1。
  • @beatngu13 哦,太棒了。我会添加一个简介,但也可以随意编辑。
猜你喜欢
  • 2011-02-15
  • 2016-08-24
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多