问题

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

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


#1 热门回答(148 赞)

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

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

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


#2 热门回答(34 赞)

一种方法是制作aListofThreads,创建并启动每个线程,同时将其添加到列表中。一旦启动所有内容,循环回列表并在每个列表中调用join()。线程完成执行的顺序无关紧要,你需要知道的是,当第二个循环完成执行时,每个线程都将完成。

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

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的concurrency utilities的所有新东西)非常灵活,上面的例子几乎没有表面上的划痕。


#3 热门回答(23 赞)

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
{
   public static void main(String[] args) throws ExecutionException, InterruptedException
   {
      //limit the number of actual threads
      int poolSize = 10;
      ExecutorService service = Executors.newFixedThreadPool(poolSize);
      List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();

      for (int n = 0; n < 1000; n++)
      {
         Future f = service.submit(new DoSomethingInAThread());
         futures.add(f);
      }

      // wait for all tasks to complete before continuing
      for (Future<Runnable> f : futures)
      {
         f.get();
      }

      //shut down the executor service so that this thread can exit
      service.shutdownNow();
   }

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

原文链接