CountDownLatch基于AQS的共享模式,用来控制一个或者多个线程等待多个线程。
CountDownLatch使用一个计数器进行实现。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。
使用案例
@org.junit.jupiter.api.Test
void testCountDownLatch() {
int nCpu = 4, queueCapacity = nCpu + 1;
ThreadPoolExecutor executorService = new ThreadPoolExecutor(nCpu,
nCpu,
0,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(queueCapacity),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(nCpu);
for (int i = 0; i < nCpu; i++) {
Runnable runnable = () -> {
try {
System.out.println("选手" + Thread.currentThread().getName() + "正在等待裁判发布口令");
cdOrder.await();
System.out.println("选手" + Thread.currentThread().getName() + "起跑了");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("选手" + Thread.currentThread().getName() + "到达终点");
cdAnswer.countDown();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
};
executorService.execute(runnable);
}
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("裁判" + Thread.currentThread().getName() + "即将发布口令");
cdOrder.countDown();
System.out.println("裁判" + Thread.currentThread().getName() + "已发送口令,正在等待所有选手到达终点");
cdAnswer.await();
System.out.println("所有选手都到达终点");
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
}
选手pool-1-thread-1正在等待裁判发布口令
选手pool-1-thread-2正在等待裁判发布口令
选手pool-1-thread-3正在等待裁判发布口令
选手pool-1-thread-4正在等待裁判发布口令
裁判main即将发布口令
裁判main已发送口令,正在等待所有选手到达终点
选手pool-1-thread-3起跑了
选手pool-1-thread-4起跑了
选手pool-1-thread-1起跑了
选手pool-1-thread-2起跑了
选手pool-1-thread-2到达终点
选手pool-1-thread-4到达终点
选手pool-1-thread-3到达终点
选手pool-1-thread-1到达终点
所有选手都到达终点
构造方法
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count); // 用的是AQS中的state
}
// 重写了AQS中的方法:尝试获取共享资源
protected int tryAcquireShared(int acquires) {
// 当状态为0,则该线程获取到该共享锁
// 刚开始肯定state被设置成count,所以肯定获取失败,只有当所有线程释放了锁(countDown)才能获取到
return (getState() == 0) ? 1 : -1;
}
// 重写了AQS中的方法:尝试释放共享资源
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
// 减少count,当检测到状态值为0时,通知同步队列中被挂起的线程
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
await方法
调用了AQS中的doAcquireSharedInterruptibly
,doAcquireSharedInterruptibly
和doAcquireShared
很相似,主要区别是doAcquireSharedInterruptibly
响应中断(抛出InterruptedException异常),而doAcquireShared
不响应中断(记录中断,最后再selfInterrupt()
)。
只要共享锁状态值不为0,则请求共享锁的线程均会添加到同步队列中,阻塞挂起,等待被通知。
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
// 重写了AQS中的方法:尝试获取共享资源
protected int tryAcquireShared(int acquires) {
// 当状态为0,则该线程获取到该共享锁
// 刚开始肯定state被设置成count,所以肯定获取失败,只有当所有线程释放了锁(countDown)才能获取到
return (getState() == 0) ? 1 : -1;
}
那这些被阻塞挂起的线程啥时候会被唤醒继续执行呢?答案就在countDown
方法中
countDown方法
释放一个资源,当检测到状态值为0时,通知同步队列中被挂起的线程
/**
* Decrements the count of the latch, releasing all waiting threads if
* the count reaches zero.
*
* <p>If the current count is greater than zero then it is decremented.
* If the new count is zero then all waiting threads are re-enabled for
* thread scheduling purposes.
*
* <p>If the current count equals zero then nothing happens.
*/
public void countDown() {
sync.releaseShared(1); // 释放一个资源
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();// doReleaseShared会唤醒同步队列中阻塞挂起的线程
return true;
}
return false;
}
// 重写了AQS中的方法:尝试释放共享资源
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
// CAS减少count
if (compareAndSetState(c, nextc))
return nextc == 0; // 当检测到状态值为0时,通知同步队列中被挂起的线程
}
}
唤醒后的线程会进行获取锁的操作。当状态值归零后,由于tryReleaseShared恒返回1,代表任何线程均可以获取共享锁成功。
也就是说:CountDownLatch是一次性的,在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用。