文章目录
前言
最近小咸儿在看项目代码时发现有用到CountDownLatch,那这个到底是什么回事呢?又用来干什么呢?让小咸儿来一探究竟。
问题
1、CountDownLatch是什么?
2、CountDownLatch有什么特性?
3、CountDownLatch适用于什么场景?
4、CountDownLatch的初始次数是否可以调整?
5、CountDownLatch底层是运行什么实现的?
简介
CountDownLatch是什么?
CountDownLatch是一个计数器闭锁,通过它可以完成类似阻塞当前线程的功能,即:一个线程或多个线程一直等待,直到其他线程执行的操作完成。
类结构:Sync为CountDownLatch的内部类
特性
构造函数
/**
* Constructs a {@code CountDownLatch} initialized with the given count.
*
* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
// Sync内部类方法,传入初始次数
Sync(int count) {
setState(count);
}
通过构造器初始化计数器的值,可实际上是把计数器的值赋值给了AQS的state,也就是用AQS的状态值来表示计数器值。
接下来看一下CountDownLatch中几个重要方法内部是如何调用AQS来实现功能的。
void await()方法
当前线程调用了CountDownLatch对象的await()方法后,当前线程会被阻塞,直到下面情况之一才会返回:
- 当所有的线程都调用了CountDownLatch对象的countDown()方法后,也就是计数器为0的时候。
- 其他线程调用了当前线程的interrupt()方法中断了当前线程,当前线程会抛出InterruptedException
异常后返回。
接下来看一下await()方法内部具体是如何实现的?
// CountDownLatch的await()方法
public void await() throws InterruptedException {
// 调用AQS的acquireSharedInterruptibly()方法
sync.acquireSharedInterruptibly(1);
}
实际上调用的是AQS的acquireSharedInterruptibly()方法
/**
* Acquires in shared mode, aborting if interrupted. Implemented
* by first checking interrupt status, then invoking at least once
* {@link #tryAcquireShared}, returning on success. Otherwise the
* thread is queued, possibly repeatedly blocking and unblocking,
* invoking {@link #tryAcquireShared} until success or the thread
* is interrupted.
* @param arg the acquire argument.
* This value is conveyed to {@link #tryAcquireShared} but is
* otherwise uninterpreted and can represent anything
* you like.
* @throws InterruptedException if the current thread is interrupted
*/
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
// 如果线程被中断则抛异常
if (Thread.interrupted())
throw new InterruptedException();
// 尝试看当前是否计数值为0,为0则返回,否则进入AQS的队列等待