Java主线程等待子线程执行完毕-CountDownLatch

主线程:

 

//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));
     }

}

 

子线程:

//子线程
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(); //正在运行的线程数减一
     }
}

 

你可能感兴趣的:(CountDownLatch)