如何在Java中使用run()启动线程的线程中等待线程完成 [英] How to wait for threads to complete in Java where threads are initiated using run()

查看:222
本文介绍了如何在Java中使用run()启动线程的线程中等待线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在启动这些线程:

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

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

How should i wait for all these threads to complete before doing some other operation.

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

My sample thread class code for one thread operation is:

public class ThreadingHDFSUsage extends Thread {

//private PhantomJSDriver driver;

private DesiredCapabilities dcaps;

 public ThreadingHDFSUsage(DesiredCapabilities dcaps) {
    // TODO Auto-generated constructor stub
     this.dcaps = dcaps;
}

public void run(){  
     System.out.println("task HDFS Usage");  

    PhantomJSDriver driver = new PhantomJSDriver(dcaps);
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
     System.out.println(".........HDFS Usage..........");
     String OverallHDFSUsage[] = null;
    try {
        OverallHDFSUsage = HDFSUsage.getWebData(driver,"http://1.2.3.4:8888/dfshealth.html#tab-overview","//*[@id=\"tab-overview\"]/table[2]/tbody/tr[2]/td","");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     String OverallHDFSUsage1 = OverallHDFSUsage[0];


 }  
}

类似地,我还有其他线程的相关代码.

Similarly, I have relevant code for other threads.

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

So, how do i wait for all these 4 thread operation to complete?

推荐答案

只需再次加入()它们:

Just join() them again:

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

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

Each join() waits for the specific thread to finish.

这篇关于如何在Java中使用run()启动线程的线程中等待线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆