如何等待多个线程完成?

如何等待多个线程完成?

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

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


阿波罗的战车
浏览 469回答 3
3回答

MMTTMM

您将所有线程放在一个数组中,启动它们,然后循环for(i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;threads.length;&nbsp;i++) &nbsp;&nbsp;threads[i].join();每个连接将阻塞,直到相应的线程完成。线程可以以与加入它们不同的顺序完成,但这不是问题:当循环退出时,所有线程都完成。

神不在的星期二

一种方法是做一个List的ThreadS,创建和启动每个线程,而将其添加到列表中。一旦启动所有内容,循环回列表并调用join()每个列表。线程完成执行的顺序并不重要,您需要知道的是,当第二个循环完成执行时,每个线程都将完成。更好的方法是使用ExecutorService及其相关方法:List<Callable> callables = ... // assemble list of Callables here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Like Runnable but can return a valueExecutorService execSvc = Executors.newCachedThreadPool();List<Future<?>> results = execSvc.invokeAll(callables);// Note: You may not care about the return values, in which case don't//&nbsp; &nbsp; &nbsp; &nbsp;bother saving them使用ExecutorService(以及来自Java 5的并发实用程序的所有新东西)非常灵活,上面的示例几乎没有表面上的划痕。

慕虎7371278

import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class DoSomethingInAThread implements Runnable{&nbsp; &nbsp;public static void main(String[] args) throws ExecutionException, InterruptedException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; //limit the number of actual threads&nbsp; &nbsp; &nbsp; int poolSize = 10;&nbsp; &nbsp; &nbsp; ExecutorService service = Executors.newFixedThreadPool(poolSize);&nbsp; &nbsp; &nbsp; List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();&nbsp; &nbsp; &nbsp; for (int n = 0; n < 1000; n++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Future f = service.submit(new DoSomethingInAThread());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;futures.add(f);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // wait for all tasks to complete before continuing&nbsp; &nbsp; &nbsp; for (Future<Runnable> f : futures)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;f.get();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; //shut down the executor service so that this thread can exit&nbsp; &nbsp; &nbsp; service.shutdownNow();&nbsp; &nbsp;}&nbsp; &nbsp;public void run()&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; // do something here&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java