java - 阻塞直到 ExecutorService 完成

标签 java multithreading concurrency blocking executorservice

<分区>

Possible Duplicates:
ExecutorService, how to wait for all tasks to finish
Java ExecutorService: awaitTermination of all recursively created tasks

有没有办法阻塞当前线程,直到 ExecutorService 完成它的所有任务?

executor.execute(task1);
executor.execute(task2);
executor.execute(task3);
executor.execute(task4);
executor.execute(task5);
// ...now I want to block until all tasks have finished executing...
System.out.println("done!")

最佳答案

对于你所有的任务,将它们放入一个 List callables 然后在它们上调用 All

ExecutorService e = ...

e.invokeAll(callables);

根据 javadocs

Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

因此线程会一直等到所有任务都完成

关于java - 阻塞直到 ExecutorService 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6374744/

相关文章:

java - 哪个 Java DOM 包装器最好或最受欢迎?

java - 数学公式的问题 - Java

c# - await 异步方法,其中完成由事件处理程序发出信号

java - 等待 Spring 应用程序中的线程完成

java - 如何防止 Web 服务 API 中的并发?

java - 从 Spring 2.5.6 升级到 3.2.6 导致 Spring Transaction Management 不再适用于 JBoss 5.1.0 和 Hibernate 3.5.6

java - 在 Java 的 JTextArea 中区分拖动和选择

c++ - 启动线程导致 abort()

scala - 线程安全地变换可变映射中的值

java - 二叉搜索树 (BST) 中的多线程插入