如何等待多个线程完成?

新手上路,请多包涵

什么是简单地等待所有线程进程完成的方法?例如,假设我有:

 public class DoSomethingInAThread implements Runnable{

    public static void main(String[] args) {
        for (int n=0; n<1000; n++) {
            Thread t = new Thread(new DoSomethingInAThread());
            t.start();
        }
        // wait for all threads' run() methods to complete before continuing
    }

    public void run() {
        // do something here
    }

}

我如何更改它,以便 main() 方法在注释处暂停,直到所有线程的 run() 方法退出?谢谢!

原文由 DivideByHero 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 692
2 个回答

你把所有线程放在一个数组中,启动它们,然后有一个循环

for(i = 0; i < threads.length; i++)
  threads[i].join();

每个连接都将阻塞,直到各自的线程完成。线程的完成顺序可能与加入它们的顺序不同,但这不是问题:当循环退出时,所有线程都已完成。

原文由 Martin v. Löwis 发布,翻译遵循 CC BY-SA 2.5 许可协议

一种方法是制作一个 ListThread s,创建并启动每个线程,同时将其添加到列表中。启动所有内容后,循环返回列表并在每个列表上调用 join() 。线程以什么顺序完成执行并不重要,您需要知道的是,到第二个循环完成执行时,每个线程都已完成。

更好的方法是使用 ExecutorService 及其相关方法:

 List<Callable> callables = ... // assemble list of Callables here
                               // Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll(callables);
// Note: You may not care about the return values, in which case don't
//       bother saving them

使用 ExecutorService(以及 Java 5 的 并发实用程序 中的所有新内容)非常灵活,上面的示例甚至只是触及表面。

原文由 Adam Batkin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题