CountDownLatch 一个神奇的计数器,您了解吗

一、CountDownLatch基础概念及案例

   1.CountDownLatch是java.util.concurrent 包下提供一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完成再执行。其本质就是一个计数器,传入一个初始的值,调用await 方法会阻塞当前线程,直到调用countDown方法计数器递减为0时,唤起等待线程,等待线程开始执行。

  2. 概念貌似比较抽象,我们一起看看CountDownLatch 使用场景。

  • 模拟100个线程并发执行,直接上代码。田径比赛一声枪响,运动健儿同时开跑。

    public class CountDownLatchTest {
        /*
         * 计数器初始化值为1
         */
        private static CountDownLatch countDownLatch = new CountDownLatch(1);
        /*** 
         * @description:  开启100个线程,并发执行 
         * @param: [args] 
         * @return: void 
         * @author: ppx
         * @date: 2023-07-21 19:31
         */ 
        public static void main(String[] args) {
            for(int i=0;  i< 100; i++){
                new Thread(()->{
                    try {
                        // 线程等待,加入共享模式队列
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName());
                },"thread"+i).start();
            }
            // 计数器减1变成0,触发阻塞线程,并发执行
            countDownLatch.countDown();
        }
        
    }
    

  • 一个线程等待其他线程执行完成后,再继续执行,类似join 方法,多用于不同线程之间的协作。

    public static void main(String[] args) {
            //计数器初始值设置为3
            CountDownLatch latch = new CountDownLatch(3);
            for (int i = 0; i < 3; i++) {
                new Thread(() -> {
                    try {
                        System.out.println("子线程:" + Thread.currentThread().getName() + "开始执行");
                        Thread.sleep(100);
                        System.out.println("子线程:" + Thread.currentThread().getName() + "执行完成");
                        // 计数器每次调用减1,当计数器为0时,唤起等待的线程
                        latch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();
    
            }
    
            try {
                System.out.println("主线程:" + Thread.currentThread().getName() + "等待子线程执行完成...");
                //阻塞主线程,直到计数器为0
                latch.await();
                System.out.println("主线程:" + Thread.currentThread().getName() + "被唤起,再次执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
  • 执行结果:

主线程:main等待子线程执行完成...子线程:Thread-0开始执行子线程:Thread-2开始执行子线程:Thread-1开始执行子线程:Thread-2执行完成子线程:Thread-1执行完成子线程:Thread-0执行完成主线程:main被唤起,再次执行

二、CountDownLatch 原理及核心方法 

  1. CountDownLatch 核心方法

方法名描述
CountDownLatch(int count)构造函数,传入计数器的初始值
await()
当前线程插入同步队列并处于等待状态, 直到计数器值为0时或线程被中断时,当前线程被唤醒并再次执行
countDown()每调用一次计数器减1,当计数器为0时,此方法唤起同步队列中等待的线程

2. 源码分析

  • CountDownLatch(int count) 方法

   CountDownLatch基于AQS 实现,本质就是设置Sync 同步状态的值,对CountDownLatch 增加了一个计数器值设置的概念。


  public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
    
  // CountDownLatch  内部基于内部类Sync  实现,Sync 继承 AbstractQueuedSynchronizer 
  private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }
        
     /**
     * Sets the value of synchronization state.
     * 设置同步状态值(技数器的值)
     * 
     */
    protected final void setState(int newState) {
        state = newState;
    }
}
  • await()方法
    
    public void await() throws InterruptedException {
            sync.acquireSharedInterruptibly(1);
     }

    调用sync的acquireSharedInterruptibly的方法

  public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
         //尝试获取同步锁,stat 小于0 执行获取同步可中断模式
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }

 获取同步锁状态,state 与 new CountDownLatch(int count)传入的计数器的值密切相关,state 不等于0才执行doAcquireSharedInterruptibly(arg)方法,把当前线程插入到同步队列中。

protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
}

 获取锁的共享模式,插入当前线程到同步队列中


private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException 
         // 将当前线程加入同步队列尾部,内部基于cas 机制
        final Node node = addWaiter(Node.SHARED);
        try {
            for (;;) {
                // 获取当前node节点的前驱节点
                final Node p = node.predecessor();
                // 如果是头部节点
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    // 判断计数器的值,同步状态值 大于0,设置为头节点
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        return;
                    }
                }
                //非头部节点 逻辑处理 检查并更新未能获取锁的节点的状态
                // 通过LockSupport.park 暂停当前线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
}
 

图片

countDown()方法

递减latch直到latch的值为0,latch值为0时,释放等待的线程。countDown()底层调用AQS子类sync的releaseShared方法。
 public void countDown() {
        sync.releaseShared(1);
  }

 releaseShared调用tryReleaseShared(arg)方法,tryReleaseShared方法获取同步锁状态并判断是否为0,为0时返回true,唤起同步队列中的线程

 public final boolean releaseShared(int arg) {
        // 尝试获取释放共享锁额状态,为true时,   
        if (tryReleaseShared(arg)) {
            //唤起同步队列中的线程        
            doReleaseShared();
            return true;
        }
        return false;
    }
protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            // 自旋的方式,通过CAS机制比较,最终判断状态(计数器)是否为0            
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c - 1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
 }
    
    

 
最终调用doReleaseShared方法,自旋唤起队列中等待的线程

private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            // 自旋设置头结点        
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                // 头节点额等待状态是否SIGNAL             
                if (ws == Node.SIGNAL) {
                    //cas 机制检查 Node.SIGNAL 与0 比较                
                    if (!h.compareAndSetWaitStatus(Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    // 唤起  后继线程 本质通过(park ,unpark )实现                
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !h.compareAndSetWaitStatus(0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

图片

三、CountDownLatch 

    CountDownLatch 的计数器只无法重置,只能使用一次。如果需要重复使用倒数计数功能,只能重建一个新的 CountDownLatch。CyclicBarrier 可以弥补这个缺陷。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值