Java主线程等待子线程执行完毕-CountDownLatch
想做的一个程序如题,主要是想统计子线程都执行完毕所用的时间,网上搜索到了CountDownLatch这个类,这个工具类可以理解为计数器。在这里用于表示正在运行的线程数,当一个子线程结束的时候,将这个计数器减一,最后在主线程的一个地方等待子线程全部执行完毕,再继续运行等待后面的程序。写了个Demo程序,如下:
//子线程 public class SubThread extends Thread{ //子线程记数器,记载着运行的线程数 private CountDownLatch runningThreadNum; public SubThread(CountDownLatch runningThreadNum){ this.runningThreadNum = runningThreadNum; } @Override public void run() { System.out.println(Thread.currentThread().getName()+"-start"); System.out.println(Thread.currentThread().getName()+"-do something"); System.out.println(Thread.currentThread().getName()+"-end"); runningThreadNum.countDown();//正在运行的线程数减一 } }
//Main主线程 public class MainThread { public static void main(String[] args) throws InterruptedException { long startTime = System.currentTimeMillis(); int threadNum = 5; //线程数 //定义正在运行的线程数 CountDownLatch runningThreadNum = new CountDownLatch(threadNum); System.out.println(Thread.currentThread().getName()+"-start"); //创建多个子线程 for (int i = 0; i < threadNum; i++) { new SubThread(runningThreadNum).start(); } //等待子线程都执行完了再执行主线程剩下的动作 runningThreadNum.await(); System.out.println(Thread.currentThread().getName()+"-end"); long endTime = System.currentTimeMillis(); System.out.println("runningTime:"+(endTime-startTime)); } }
main-start Thread-0-start Thread-0-do something Thread-0-end Thread-1-start Thread-1-do something Thread-1-end Thread-2-start Thread-2-do something Thread-2-end Thread-4-start Thread-3-start Thread-4-do something Thread-3-do something Thread-4-end Thread-3-end main-end runningTime:16
看到打印的结果,满足我现在的要求。笔记下~~