有什么方法可以简单地等待所有线程进程完成?例如,假设我有:
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()
方法退出?谢谢!
您将所有线程放入一个数组,全部启动,然后进行循环
for(i = 0; i < threads.length; i++)
threads[i].join();
每个连接将阻塞,直到相应的线程完成为止。线程的完成顺序可能不同于您加入线程的顺序,但这不是问题:退出循环时,所有线程均已完成。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句