• CountDownLatch


    跟Semaphore一样,也是通过AQS的共享锁机制实现的,用于一个或多个线程等待其他线程完成的一组操作。原理如下:

    1、用AQS的state变量表示操作个数

    2、用AQS的共享锁机制完成唤醒

    3、等待锁的线程使用acquireShared方法获取共享锁等待

    4、操作线程使用releaseShared方法用于唤醒等待共享锁的线程

    public class CountDownLatch {
       
        private static final class Sync extends AbstractQueuedSynchronizer {
            private static final long serialVersionUID = 4982264981922014374L;
    
            Sync(int count) {
                setState(count);
            }
    
            int getCount() {
                return getState();
            }
    		//获取共享锁子类实现
            protected int tryAcquireShared(int acquires) {
                return (getState() == 0) ? 1 : -1;  //AQS state为0时,获取成功,其他失败
            }
    		//释放共享锁
            protected boolean tryReleaseShared(int releases) {
                //count递减
                for (;;) {
                    int c = getState();
                    if (c == 0)  //已经为0了,没有可释放的,返回false
                        return false;
                    int nextc = c-1;
                    if (compareAndSetState(c, nextc))  //CAS更新state,为0时唤醒AQS阻塞队列节点
                        return nextc == 0;
                }
            }
        }
    
        private final Sync sync;
    
      
        public CountDownLatch(int count) {
            if (count < 0) throw new IllegalArgumentException("count < 0");
            this.sync = new Sync(count);
        }
    
       
        public void await() throws InterruptedException {
            sync.acquireSharedInterruptibly(1);
        }
    
        
        public boolean await(long timeout, TimeUnit unit)
            throws InterruptedException {
            return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
        }
    
       
        public void countDown() {
            sync.releaseShared(1);
        }
    
        public long getCount() {
            return sync.getCount();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

  • 相关阅读:
    JRZB-R02保持防跳继电器
    评分和排名算法
    讲清楚两个简单的概念之进程、线程
    React中插槽处理机制
    工作任务“杂乱难”?这个小工具帮你轻松搞定!
    c 摄像头利用v4l2直接生成avi视频(不利用ffmpeg)
    力矩电机控制基本原理
    ArkTs快速入门
    将数组拆分成斐波那契序列
    登录功能注意的点
  • 原文地址:https://blog.csdn.net/zhang527294844/article/details/133989501