线程等到所有线程都使用java返回输出?

时间:2011-07-04 09:57:32

标签: java multithreading

  

可能重复:
  How to wait for a set of threads to complete?

我想运行三个线程,每个线程调用不同的类。这些类进行一些处理并返回Boolean值,我想等到所有三个线程都返回它们的输出。我想知道如何使用Java实现它。

由于

6 个答案:

答案 0 :(得分:4)

您可以使用Thread.join()来执行此操作:

Thread[] threads = new Thread[numOfThreads];
for (int i = 0; i < threads.length; i++) {
    threads[i] = new Thread(new Runnable() {
        public void run() {
            System.out.println("xxx");
        }
    });
    threads[i].start();
}

for (int i = 0; i < threads.length; i++) {
    try {
        threads[i].join();
    } catch (InterruptedException e) {
    }
}

为您的解决方案

Thread[] threads = new Thread[3];
threads[i] = new Thread(new Runnable() {
        ...
}).start();
threads[i] = new Thread(new Runnable() {
        ...
}).start();
threads[i] = new Thread(new Runnable() {
        ...
}).start();

for (int i = 0; i < threads.length; i++) {
    try {
        threads[i].join();
    } catch (InterruptedException e) {
    }
}

答案 1 :(得分:2)

如果您使用的是ExecutorService,则可以执行

 ExecutorService es = /* create a reusable thread pool */

 List<Future> futures = new ArrayList<Future>();
 futures.add(es.submit(myRunnable1));
 futures.add(es.submit(myRunnable2));
 futures.add(es.submit(myRunnable3));
 for(Future f: futures) f.get(); // wait for them to finish.

如果要返回布尔值,则应使用Callable。您也可以使用invokeAll

 ExecutorService es = /* create a reusable thread pool */

 List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
 es.invokeAll(Arrays.asList(
    new Callable<Boolean>() {
        public Boolean call() {
             return true;
        }
    },
    new Callable<Boolean>() {
        public Boolean call() {
             return false;
        }
    },
    new Callable<Boolean>() {
        public Boolean call() {
             return true;
        }
    }
 ));

 for(Future<Boolean> f: futures) {
      Boolean result = f.get();
 }

答案 2 :(得分:0)

线程有join方法。如果主线程在线程t上调用该方法,则主线程将等到t完成。

请参阅http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#join()

答案 3 :(得分:0)

您可以使用“障碍”(请参阅​​CyclicBarrier了解Java API中的实现)。或者,如果您只想获得输出,但在处理输出之前不需要全部完成输出,则可以使用Future表示计算,如果需要,将在获取结果时阻止计算。

答案 4 :(得分:0)

您可以使用Thread.join(),如下所示: -

Thread t1 = new Thread(myRunnable1);
Thread t2 = new Thread(myRunnable2);
Thread t3 = new Thread(myRunnable3);

t1.start();
t2.start();
t3.start();

t1.join();
t2.join();
t3.join();

//do something when all 3 threads finish

我希望这可能有助于达到你的要求。

此致

Charlee Ch。

答案 5 :(得分:0)

请查看ExecutorCompletionService

中的示例