如何等待多个线程完成? [英] How to wait for a number of threads to complete?

查看:138
本文介绍了如何等待多个线程完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is a way to simply wait for all threaded process to finish? For example, let's say I have:

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()方法退出?谢谢!

How do I alter this so the main() method pauses at the comment until all threads' run() methods exit? Thanks!

推荐答案

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

You put all threads in an array, start them all, and then have a loop

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

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

Each join will block until the respective thread has completed. Threads may complete in a different order than you joining them, but that's not a problem: when the loop exits, all threads are completed.

这篇关于如何等待多个线程完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆