JUC源码解析-CountDownLatch

CountDownLatch允许一个或多个线程等待其它线程完成操作。

CountDownLatch的构造函数接收一个int类型的参数作为计数器,想等待N个任务线程完成就传N。当countDown方法被调用N就会减一,await方法会阻塞当前线程直到N变为0。

主要的功能就是通过await()方法来阻塞线程,然后等待计数器减少到0了,再唤起那些等待的线程继续;即你想要某些线程等待另一些线程执行完再执行,就可以使用CountDownLatch。
先来看看用法:

//三个线程阻塞直到主线程执行完
    public void test1() {
        final CountDownLatch latch = new CountDownLatch(1);

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " wait;");
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " start");
            }).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }

//主线程阻塞等待直到三个线程都执行完
    public void test2() {
        final CountDownLatch latch = new CountDownLatch(3);

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " start");
                latch.countDown();
            }).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("All end");
    }

在举一个创建Zookeeper实例的例子

    protected ZooKeeper zooKeeper;

    // 阻塞直到连接成功
    private CountDownLatch latch = new CountDownLatch(1);

    /**
     * 连接ZK服务器
     * @param address 地址
     */
    protected void connectServer(String address) {
        try {
            this.zooKeeper = new ZooKeeper(address, ZK_SESSION_TIMEOUT, event -> {
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    if (Watcher.Event.EventType.None == event.getType()) {
                        latch.countDown();
                        log.info("ZK连接成功");
                    }
                }
            });
            log.info("开始连接ZK服务器");
            latch.await();
        } catch (IOException | InterruptedException e) {
            log.error("", e);
        }
    }

源码

下面出现的很多方法都在之前AQS的文章里分析过了,这里就不重复了。

构造函数:同步状态state的值在CountDownLatch构造函数中赋值(AQS为同步状态提供了getState,setState方法,state是volatile修饰)。

    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值