CountDownLatch解读
- 是基于AQS原理,共享锁的一种实现,构造函数里的count值代表计数器,会将count赋值给state。
- CountDownLatch不可重入。
- 通过await()来阻塞线程。countDown使计数器-1,当count为0时候所有await的线程会同时获取锁。
实现原理
CountDownLatch有一个内部类Sync,该类继承了AQS,await()方法和countDown方法都是调用Sync的tryAcquireShared和tryReleaseShared
共享锁获取锁-tryAcquireShared
CountDownLatch掉用await()实际上是调用sync的acquireSharedInterruptibly,最终会调用AQS中的doAcquireSharedInterruptiblyState,在该方法中调用doAcquireSharedInterruptibly,在改方法中,会调用CountDownLatch实现的tryAcquireShared方法如果state==0返回1,否则-1,其中代码和逻辑如下:
1 | private void doAcquireSharedInterruptibly(int arg) |
共享锁释放-tryAcquireShared
CountDownLatch调用countDown()时候回调用sync.releaseShared(1),实际是AQS的releaseShared(int args)方法,如果返回true即state==0,在该方法中会调用doReleaseShared(),获取锁和传播获取锁的流程
CountDownLatch中的Sync的tryReleaseShared:
1 | protected boolean tryReleaseShared(int releases) { |
AQS中的releaseShared代码
1 | public final boolean releaseShared(int arg) { |