什么是简单地等待所有线程进程完成的方法?例如,假设我有:
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 许可协议
你把所有线程放在一个数组中,启动它们,然后有一个循环
每个连接都将阻塞,直到各自的线程完成。线程的完成顺序可能与加入它们的顺序不同,但这不是问题:当循环退出时,所有线程都已完成。