JUC 源码分析之CountDownLatch

简介: 1 概述CountDownLatch是一个同步辅助类,通过AQS实现的一个闭锁。在其他线程完成它们的操作之前,允许一个多个线程等待。简单来说,CountDownLatch中有一个锁计数,在计数到达0之前,线程会一直等待。

1 概述

CountDownLatch是一个同步辅助类,通过AQS实现的一个闭锁。
在其他线程完成它们的操作之前,允许一个多个线程等待。
简单来说,CountDownLatch中有一个锁计数,在计数到达0之前,线程会一直等待。


img_31293c48192893b342a53c8e9d2ac6be.png
运行机制

2 数据结构

img_f9ed0cdbf3c68f93968601c26d051398.png
继承关系

CountDownLatch是一个"共享锁”",内部定义了自己的同步器 SyncSync继承自AQS,实现了 tryAcquireSharedtryReleaseShared两个方法。

CountDownLatch中的锁是响应中断的,如果线程在对锁进行操作期间发生中断,会直接抛出InterruptedException

3 源码解析

img_164d7c9c1e5813f54a4460a4272201b1.png
构造方法

CountDownLatch中的count其实就是AQS的state
img_b3d8222b54019a20591b05f92540ac9b.png

从构造函数中可以看出, CountDownLatch"锁计数"本质上就是AQS的资源数 state

下面我们将通过await()countDown()分析CountDownLatch的"latch"原理

3.1 await()

img_899e33fcce433512259b646c0efb5eea.png
await()

img_5c747488dc5e4fb1eb6903fb79e3a33c.png
AQS中`acquireSharedInterruptibly(1)`的实现

img_99961c4971ae29b9a41e6749ca8b89ee.png
tryAcquireShared在CountDownLatch中的实现

await()的实现非常简单,就是通过对资源 state剩余量 state==0 ? 1 : -1来判断是否获取到锁。
tryAcquireShared函数规定返回值类型

  • 成功获取并且还有可用资源返回正数
  • 成功获取但是没有可用资源时返回0
  • 获取资源失败返回一个负数

即只要state!=0,线程就进入等待队列阻塞

countDown()

img_5f03f38a439ece928e009468041f1728.png

img_1604e356b49150911baa4c4d595743ca.png

img_33311f4f4720a3c3ba3a964018dbe6d0.png

说明:如果释放资源后 state==0,说明已经到达latch,此时就可以调用 doReleaseShared唤醒等待的线程。

相对其他同步类来说,CountDownLatch可以说是最简单的同步类实现了。它完全依赖了AQS,只要理解了AQS,那么理解它就不成问题

package java.util.concurrent;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * A synchronization aid that allows one or more threads to wait until
 * a set of operations being performed in other threads completes.
 *
 * <p>A {@code CountDownLatch} is initialized with a given <em>count</em>.
 * The {@link #await await} methods block until the current count reaches
 * zero due to invocations of the {@link #countDown} method, after which
 * all waiting threads are released and any subsequent invocations of
 * {@link #await await} return immediately.  This is a one-shot phenomenon
 * -- the count cannot be reset.  If you need a version that resets the
 * count, consider using a {@link CyclicBarrier}.
 *
 * <p>A {@code CountDownLatch} is a versatile synchronization tool
 * and can be used for a number of purposes.  A
 * {@code CountDownLatch} initialized with a count of one serves as a
 * simple on/off latch, or gate: all threads invoking {@link #await await}
 * wait at the gate until it is opened by a thread invoking {@link
 * #countDown}.  A {@code CountDownLatch} initialized to <em>N</em>
 * can be used to make one thread wait until <em>N</em> threads have
 * completed some action, or some action has been completed N times.
 *
 * <p>A useful property of a {@code CountDownLatch} is that it
 * doesn't require that threads calling {@code countDown} wait for
 * the count to reach zero before proceeding, it simply prevents any
 * thread from proceeding past an {@link #await await} until all
 * threads could pass.
 *
 * <p><b>Sample usage:</b> Here is a pair of classes in which a group
 * of worker threads use two countdown latches:
 * <ul>
 * <li>The first is a start signal that prevents any worker from proceeding
 * until the driver is ready for them to proceed;
 * <li>The second is a completion signal that allows the driver to wait
 * until all workers have completed.
 * </ul>
 *
 *  <pre> {@code
 * class Driver { // ...
 *   void main() throws InterruptedException {
 *     CountDownLatch startSignal = new CountDownLatch(1);
 *     CountDownLatch doneSignal = new CountDownLatch(N);
 *
 *     for (int i = 0; i < N; ++i) // create and start threads
 *       new Thread(new Worker(startSignal, doneSignal)).start();
 *
 *     doSomethingElse();            // don't let run yet
 *     startSignal.countDown();      // let all threads proceed
 *     doSomethingElse();
 *     doneSignal.await();           // wait for all to finish
 *   }
 * }
 *
 * class Worker implements Runnable {
 *   private final CountDownLatch startSignal;
 *   private final CountDownLatch doneSignal;
 *   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
 *     this.startSignal = startSignal;
 *     this.doneSignal = doneSignal;
 *   }
 *   public void run() {
 *     try {
 *       startSignal.await();
 *       doWork();
 *       doneSignal.countDown();
 *     } catch (InterruptedException ex) {} // return;
 *   }
 *
 *   void doWork() { ... }
 * }}</pre>
 *
 * <p>Another typical usage would be to divide a problem into N parts,
 * describe each part with a Runnable that executes that portion and
 * counts down on the latch, and queue all the Runnables to an
 * Executor.  When all sub-parts are complete, the coordinating thread
 * will be able to pass through await. (When threads must repeatedly
 * count down in this way, instead use a {@link CyclicBarrier}.)
 *
 *  <pre> {@code
 * class Driver2 { // ...
 *   void main() throws InterruptedException {
 *     CountDownLatch doneSignal = new CountDownLatch(N);
 *     Executor e = ...
 *
 *     for (int i = 0; i < N; ++i) // create and start threads
 *       e.execute(new WorkerRunnable(doneSignal, i));
 *
 *     doneSignal.await();           // wait for all to finish
 *   }
 * }
 *
 * class WorkerRunnable implements Runnable {
 *   private final CountDownLatch doneSignal;
 *   private final int i;
 *   WorkerRunnable(CountDownLatch doneSignal, int i) {
 *     this.doneSignal = doneSignal;
 *     this.i = i;
 *   }
 *   public void run() {
 *     try {
 *       doWork(i);
 *       doneSignal.countDown();
 *     } catch (InterruptedException ex) {} // return;
 *   }
 *
 *   void doWork() { ... }
 * }}</pre>
 *
 * <p>Memory consistency effects: Until the count reaches
 * zero, actions in a thread prior to calling
 * {@code countDown()}
 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
 * actions following a successful return from a corresponding
 * {@code await()} in another thread.
 *
 * @since 1.5
 * @author Doug Lea
 */
public class CountDownLatch {
    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        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;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

    private final Sync sync;
 /**
     * Returns the current count.
     *
     * <p>This method is typically used for debugging and testing purposes.
     *
     * @return the current count
     */
    public long getCount() {
        return sync.getCount();
    }

    /**
     * Returns a string identifying this latch, as well as its state.
     * The state, in brackets, includes the String {@code "Count ="}
     * followed by the current count.
     *
     * @return a string identifying this latch, as well as its state
     */
    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}
目录
相关文章
|
7月前
|
消息中间件 监控 Java
JUC第二十六讲:JUC工具类: CountDownLatch详解
JUC第二十六讲:JUC工具类: CountDownLatch详解
|
9月前
|
资源调度
JUC并发编程之同步器(Semaphore、CountDownLatch、CyclicBarrier、Exchanger、CompletableFuture)附带相关面试题
1.Semaphore(资源调度) 2.CountDownLatch(子线程优先) 3.CyclicBarrier(栅栏) 4.Exchanger(公共交换区) 5.CompletableFuture(异步编程)
103 0
|
7月前
|
API
JUC第二十七讲:JUC工具类: CyclicBarrier详解
JUC第二十七讲:JUC工具类: CyclicBarrier详解
|
Java API
Java并发之CountDownLatch
Java并发之CountDownLatch
132 1
Java并发之CountDownLatch
|
Java
Java多线程-CountDownLatch、Semaphone、CyclicBarrier入门
多线程CountDownLatch、Semaphone、CyclicBarrier讲解
155 1
Java多线程-CountDownLatch、Semaphone、CyclicBarrier入门
|
安全 Dubbo Java
JUC系列(七)| JUC三大常用工具类CountDownLatch、CyclicBarrier、Semaphore
JUC系列(七)| JUC三大常用工具类CountDownLatch、CyclicBarrier、Semaphore
418 0
JUC系列(七)| JUC三大常用工具类CountDownLatch、CyclicBarrier、Semaphore
|
算法 Java 数据库
Java并发:同步工具类详解(CountDownLatch、CyclicBarrier、Semaphore)
Java并发:同步工具类详解(CountDownLatch、CyclicBarrier、Semaphore)
262 0
|
Java uml
JUC之ThreadPoolExecutor实现原理分析
ThreadPoolExecutor工作流程 JDK1.5中引入了线程池,合理地利用线程池能有效的提高程序的运行效率,但不当的使用线程池也会带来致命的危害。作为使用最多的ThreadPoolExecutor,很有必要深入理解的其源码与实现原理。 先看一下ThreadPoolExecutor是如何工作的,暂时不看源码,这样会先有一个比较直观的印象有利于后面深入分析源码。 既然是线程池那么提交任务后一定要创建线程用于执行任务,ThreadPoolExecutor创建线程执行提交任务的流程如下。
78 0
JUC之ThreadPoolExecutor实现原理分析