JDK1.8中CountDownLatch 源码(注释已经翻译成中文)
- 并发
- 时间:2020-03-16 16:42
- 1699人已阅读
简介
以下是countdownlatch源码。注释已经翻译成中文:package java.util.concurrent;import java.util.concurrent.locks.AbstractQueuedSynchronizer;/** * A synchronization aid that allows&
🔔🔔🔔好消息!好消息!🔔🔔🔔
有需要的朋友👉:联系凯哥
以下是countdownlatch源码。注释已经翻译成中文:
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}. * 用给定的count之来初始化countDownLatch对象。调用 countDown方法直到当前count减少到0的时候,await方法就会被释放掉(不在阻塞) * 这是一次性的倒计时器,无法重置(reset)计数器.如果你需要重置count的话,可以使用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. *CountDownLatch是一个通用的同步工具,适用于很多场景。 *CountDownLatch在初始化的时候,计数器设置为1的时候,可以作为一个简单的开关。 *所有调用await方法的线程都在等待着。直到调用countDown方法的时候,线程才不会继续等待。 *初始化一个计数器为N的CountDownLatch对象的含义:有可能是一个线程在等待其他N个线程完成某一个操作 *或者是某个操作完成N次 * * <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 { /** * CountDownLatch 内部类 * Synchronization control For CountDownLatch. *倒计时锁存器的同步控制。 * Uses AQS state to represent count. *采用AQS状来代表计数的。 */ 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; /** * Constructs a {@code CountDownLatch} initialized with the given count. *基于给定的count来初始化CountDownLatch对象 * @param count the number of times {@link #countDown} must be invoked * before threads can pass through {@link #await} * 参数说明:在调用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); } /** * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}. * * <p>If the current count is zero then this method returns immediately. * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of two things happen: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * @throws InterruptedException if the current thread is interrupted * while waiting */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** * 是否可以唤起其他线程方法 * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}, * or the specified waiting time elapses. *使当前线程等待,直到计时器已倒计时为零,除非线程抛出interrupted异常或者指定的等待时间已过。 * * <p>If the current count is zero then this method returns immediately * with the value {@code true}. * 如果当前计数器count是零的话,这个方法立马返回ture * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of three things happen: *如果当前计数大于零,则当前由于线程调度的目的,线程被禁用,并且存在在以下三种情况发生之前休眠: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>The specified waiting time elapses. * 1:由于调用了countDown方法是的count的值为零; * 2:或由于当前线程中其他线程抛出了 interrupts异常(中断异常); * 3:或指定的等待时间已过。 * </ul> * * <p>If the count reaches zero then the method returns with the * value {@code true}. * 如果计数为零,则方法返回值 * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * 如果当前线程出现以下情况,当前线程中断的状态将会被清除掉 * 1:在调用await此方法的时候,线程被标记为中断状态的; * 2:或者在等待的过程中抛出了中断异常的时候。 * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * 如果设置等待的时间超时,返回false. * 如果运行次数小于或者是等于0,这个方法就不会再等待了 * * @param timeout the maximum time to wait:超时等待的最长时间 * @param unit the time unit of the {@code timeout} argument 超时等待时间单位 * @return {@code true} if the count reached zero and {@code false} * if the waiting time elapsed before the count reached zero * @throws InterruptedException if the current thread is interrupted * while waiting */ public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } /** * 计数器减少1的方法。 * Decrements the count of the latch, releasing all waiting threads if * the count reaches zero. * 计数器减少1的方法,如果计数达到零,则释放所有等待的线程。 * <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); } /** * 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() + "]"; } }