CountDownLatch-学习

113 阅读1分钟

简介

CountDownLatch:可以理解为计数器,当计数器减为0时,代表资源可以访问。就像倒计时跑步一样,3,2,1 发号枪响起开始跑;

CountDownLatch共享锁模式;

基本成员

  • count

初始化CountDownLatch参数,最终会设置到AQS.state,表示计数器的值

  • Sync

同步器,继承AQS,实现tryAcquireShared、tryReleaseShared 共享锁方法

主要方法

  • countDown
/**
* 计数器-1,调用AQS的释放资源模版方法
*/
public void countDown() {
    sync.releaseShared(1);
}
  • await
/**
* 等待计数器归0,调用AQS的获取资源模版方法
*/
public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}
  • await(timeout)
/**
* 规定时间内等待计数器归0,调用AQS的获取资源模版方法
*/
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
   return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
  • tryAcquireShared
/**
* 获取资源,计数器归0,代表可以获取
*/
protected int tryAcquireShared(int acquires) {
    return (getState() == 0) ? 1 : -1;
}
  • tryReleaseShared
/**
* 释放资源,因为是共享锁,设计到多线程同时操作,所以有 自旋+CAS更改状态
*/
protected boolean tryReleaseShared(int releases) {
   // 自旋
    for (;;) {
        int c = getState();
        if (c == 0)
            return false;
        // 状态递减1
        int nextc = c-1;
        // CAS更新状态
        if (compareAndSetState(c, nextc))
            // 计数器为0,代表可以唤醒await的线程了
            return nextc == 0;
    }
}

问题