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

标签 java multithreading

<分区>

Possible Duplicate:
How to wait for a set of threads to complete?

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

谢谢

最佳答案

您可以使用 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) {
    }
}

关于java - 线程等到所有线程使用 java 返回输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6569893/

相关文章:

java - StreamSource开启时刻

java - Spring /处女座 - java swing : JDialog starts behind other windows

Java同步帮助请求

c++ - VC2010 的 static init 线程安全吗?

c++ - 什么会导致 _mm_setzero_si128() 变为 SIGSEGV?

c++ - 同时多次运行一个进程

Java x32 与 x64 JVM 崩溃

java - 无法在 Eclipse 的“创建 Servlet”对话框中选择项目

java 8 lambda 与先前的值

java - 我应该在我的 java 视频应用程序中实现消费者/生产者模式吗?如果是,如何实现?