深入理解CountDownLatch

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中的doAcquireSharedInterruptiblydoAcquireSharedInterruptiblydoAcquireShared很相似,主要区别是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使用完毕后,它不能再次被使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值