如何在Java中等待线程完成使用run()启动线程

时间:2015-10-28 17:40:26

标签: java multithreading

我正在开始这些主题:

x = [1, 1, 2, 2, 3]
y = [1, 2]
z = [n for n in y if (n in x) and x.remove(n)] + x
print(z)  # -> [1, 2, 3]

x = [1, 1, 1, 2]
y = [1]
z = [n for n in y if (n in x) and x.remove(n)] + x
print(z)  # -> [1, 1, 2]

在进行其他操作之前,我应该如何等待所有这些线程完成。

我的一个线程操作的示例线程类代码是:

          ThreadingHDFSUsage HDFSUsage=new ThreadingHDFSUsage(dcaps);  
          ThreadingRAMandContainers RAMandContainers=new ThreadingRAMandContainers(dcaps);  
          ThreadingCoreNodesHDFSUsage CoreNodesHDFSUsage=new ThreadingCoreNodesHDFSUsage(dcaps);
          ThreadingApplicationMonitoring ApplicationMonitoring= new ThreadingApplicationMonitoring(dcaps);

同样,我有其他线程的相关代码。

那么,我如何等待所有这4个线程操作完成?

3 个答案:

答案 0 :(得分:2)

再次加入()他们:

HDFSUsage.join();  
RAMandContainers.join();
CoreNodesHDFSUsage.join();
ApplicationMonitoring.join();

每个join()等待特定线程完成。

答案 1 :(得分:0)

JDK CompletionService包中还有concurrent。要使用它,您需要从显式Threads切换到任务,表示为Callable<ResultType>Runnable的实例。虽然代码可能看起来稍微复杂一些,但是一旦你习惯了它就很方便了:

import java.util.concurrent.*;

class Test {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CompletionService<String> completionService = new ExecutorCompletionService<>(Executors.newCachedThreadPool());
        completionService.submit(() -> {
            Thread.sleep(5000);
            return "sleeped for 5000 millis";
        });
        completionService.submit(() -> {
            Thread.sleep(1000);
            return "sleeped for 1000 millis";
        });
        // etc
        System.out.println("Completed: " + completionService.take().get());
        System.out.println("Completed: " + completionService.take().get());
    }

}

答案 2 :(得分:0)

其他两个答案都是正确的,但为了完整起见,还有另一种方法可以使用Semaphore做你想做的事情。此方法不会产生与任何其他答案不同的结果,但如果您的任何线程在返回之后必须在获得所需结果之后执行某些昂贵的操作,则可能会更快。在每个线程内部,一旦所有相关工作完成,请立即致电s.release()。您的控制器线程可能如下所示......

Semaphore s = new Semaphore(0);
//start all four of your threads here and pass 's' to each
s.acquire(4);

...你的工作线程可能如下所示:

@Override
public void run(){
    //compute results
    s.release(1);
    //do expensive cleanup and return
}