如何使用ExecutorService等待所有线程完成?我需要一次执行一些任务4,如下所示:ExecutorService taskExecutor = Executors.newFixedThreadPool(4);while(...) {
taskExecutor.execute(new MyTask());}//...wait for completion somehow一旦它们全部完成,如何通知我?现在,我想不出有什么比设置一些全局任务计数器并在每个任务结束时减少它更好的了,然后在无限循环中监视这个计数器使其变为0;或者得到一个期货列表和无限循环监视器是对所有任务都是Done的。没有无限循环的更好的解决方案是什么?谢谢。
3 回答
智慧大石
TA贡献1946条经验 获得超3个赞
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);ExecutorService taskExecutor = Executors.newFixedThreadPool(4);while(...) { taskExecutor.execute(new MyTask());}try { latch.await();} catch (InterruptedException E) { // handle}
latch.countDown();
米脂
TA贡献1836条经验 获得超3个赞
ExecutorService.invokeAll()
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);List<Callable<?>> tasks; // your tasks// invokeAll() returns when all tasks are completeList<Future<?>> futures = taskExecutor.invokeAll(tasks);
偶然的你
TA贡献1841条经验 获得超3个赞
ExecutorService
shutdown()
awaitTermination()
:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);while(...) { taskExecutor.execute(new MyTask());}taskExecutor.shutdown();try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);} catch (InterruptedException e) { ...}
添加回答
举报
0/150
提交
取消