一个方法 简单快速理解CountDownLatch 用法

CountDownLatch 用法




import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch mainLatch = new CountDownLatch(2);
        CountDownLatch childLatch = new CountDownLatch(5);

        // 依次创建并启动处于等待状态的5个MyRunnable线程
        for (int i = 0; i < 5; ++i) {
            new Thread(new MyRunnable(mainLatch, childLatch)).start();
        }
        Thread.sleep(100); // 先让子线程抢资源
        mainLatch.countDown(); // 主线程执行
        System.out.println("主线程完成一个 开始等待");
        Thread.sleep(2000);
        System.out.println("计数一次再次执行, 此时countDown 的count 被减到0 其他await的线程可以执行");
        mainLatch.countDown();
        childLatch.await(); // 等待childLatch 被countDown5次
        System.out.println("Bingo!");
    }



}
class MyRunnable implements Runnable {

    private final CountDownLatch mainLatch;
    private final CountDownLatch childLatch;

    public MyRunnable(CountDownLatch mainLatch, CountDownLatch childLatch) {
        this.mainLatch = mainLatch;
        this.childLatch = childLatch;
    }

    public void run() {
        try {
            System.out.println("其他线程执行 但是碰到await 开始等待");
            mainLatch.await();//等待主线程执行两次  countDown() 再往下执行
            System.out.println("每个线程开始处理自己的工作");
            childLatch.countDown();//完成预期工作,countDown() 一下
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

 

执行结果 

一个方法 简单快速理解CountDownLatch 用法_第1张图片

文章参考 https://blog.csdn.net/huang_wu_yao_xin/article/details/82704257

你可能感兴趣的:(java)