测试countDownLatch

        package com.neusoft;

import java.util.concurrent.CountDownLatch;

/**
 * 让主线程等待所有其他线程执行完毕,再去执行,使用场景汇总子线程执行完的结果,统一处理。
 * CountDownLatch 类似于join的阻塞
 * @author Administrator
 */
public class TestCountDownLatch {
    static CountDownLatch countDownLatch = new CountDownLatch(2);

    static Thread firstThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("first thread count down");
            countDownLatch.countDown();
        }
    });
    static Thread secondThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("second thread count down");
            countDownLatch.countDown();
        }
    });
    public static void main(String[] args) {
        firstThread.start();
        secondThread.start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main thread run");
    }
}
      

输出:

        first thread count down
second thread count down
main thread run
      



去掉await()

        main thread run
second thread count down
first thread count down
      

你可能感兴趣的:(测试countDownLatch)