Java多线程--让主线程等待所有子线程执行完毕代码

采用CountDownLatch类来实现

 

 

主线程 

 

package test;

import java.util.concurrent.CountDownLatch;

public class Main {

 /**
  *
  * @author Administrator/2012-3-1/上午09:36:55
  */
 public static void main(String[] args) {

  int threadNum = 10;
  CountDownLatch threadSignal = new CountDownLatch(threadNum);// 初始化countDown

  for (int i = 0; i < threadNum; i++) {// 开threadNum个线程

   Thread t = new ImportThread(i,threadSignal);
   t.start();
  }
  try {
   threadSignal.await();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }// 等待所有子线程执行完
  System.out.println(Thread.currentThread().getName() + "结束.");// 打印结束标记

 }

}

 

 

子线程:

package test;

import java.util.concurrent.CountDownLatch;

public class ImportThread extends Thread {
 private CountDownLatch threadsSignal;
 
 private  int index;

 public ImportThread(int index,CountDownLatch threadsSignal) {
  this.threadsSignal = threadsSignal;
  this.index=index;
 }

 @Override
 public void run() {
  System.out.println(Thread.currentThread().getName() + "开始...");
  // Do somethings
  System.out.println(Thread.currentThread().getName()+"do execute ...");
  threadsSignal.countDown();// 线程结束时计数器减1
  System.out.println(Thread.currentThread().getName() + "结束. 还有" + threadsSignal.getCount() + " 个线程");
 }
}

 

 


 

上一篇:【No.12 C++参数传递方式造成的对象切割】


下一篇:从零开始搭建Jenkins+Docker自动化集成环境