一、CyclicBarrier是什么?
CyclicBarrier,一个同步辅助类,在API中是这么介绍的:
它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待, 此时 CyclicBarrier 很有用。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。 通俗点讲就是:让一组线程到达一个屏障时被阻塞,直到最后一个线程到达屏障时, 屏障才会开门,所有被屏障拦截的线程才会继续干活。
允许一组线程互相等待,直到到达某个公共屏障点,才会进行后续任务。
二、代码实例
1.飞机起飞示例
private static CyclicBarrierT1 cyclicBarrier;
static class CyclicBarrierThread extends Thread{
@Override
public void run() {
log.info(Thread.currentThread().getName() + "上飞机了");
//等待
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
/**
* 比如飞机起飞只有等所有的人到齐了才会起飞
*/
cyclicBarrier = new CyclicBarrierT1(5, new Runnable() {
@Override
public void run() {
log.info("人到齐了,飞机起飞吧....");
}
});
for(int i = 0 ; i < 5 ; i++){
new CyclicBarrierThread().start();
}
}
2.源码分析
package com.yl.springboottest.consurrency.cyclicbarrier;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 描述: J.U.C之并发工具类:CyclicBarrier
*
* @author: yanglin
* @Date: 2020-11-27-9:48
* @Version: 1.0
*/
@Slf4j
public class CyclicBarrierT1 {
/**
* Each use of the barrier is represented as a generation instance.
* The generation changes whenever the barrier is tripped, or
* is reset. There can be many generations associated with threads
* using the barrier - due to the non-deterministic way the lock
* may be allocated to waiting threads - but only one of these
* can be active at a time (the one to which {@code count} applies)
* and all the rest are either broken or tripped.
* There need not be an active generation if there has been a break
* but no subsequent reset.
*
* 屏障的每次使用都表示为一个生成实例。只要安全栅跳闸或复位,发电量就会改变。
* 由于锁可能分配给等待线程的非确定性方式,可能会有许多代与线程关联,
* 但每次只能有一个处于活动状态(即{@code count}应用的线程),
* 其余的要么中断要么被触发。如果有中断但没有后续重置,则不需要激活生成。
*
* 如果一个线程处于等待状态时,如果其他线程调用reset(),或者调用的barrier原本就是被损坏的,
* 则抛出BrokenBarrierException异常。同时,任何线程在等待时被中断了,
* 则其他所有线程都将抛出BrokenBarrierException异常,并将barrier置于损坏状态。
* 同时,Generation描述着CyclicBarrier的更显换代。在CyclicBarrier中,
* 同一批线程属于同一代。当有parties个线程到达barrier,generation就会被更新换代。
* 其中broken标识该当前CyclicBarrier是否已经处于中断状态。
*/
private static class Generation {
boolean broken = false;
}
/** The lock for guarding barrier entry 用来守卫栅栏入口的锁 重入锁*/
private final ReentrantLock lock = new ReentrantLock();
/** Condition to wait on until tripped 等待跳闸的条件 */
private final Condition trip = lock.newCondition();
/** The number of parties 当事人人数(拦截线程的数量) */
private final int parties;
/** The command to run when tripped 跳闸时运行的命令 */
private final Runnable barrierCommand;
/** The current generation 当事人(线程) */
private Generation generation = new Generation();
/**
* Number of parties still waiting. Counts down from parties to 0
* on each generation. It is reset to parties on each new
* generation or when broken.
*/
private int count;
/**
* Updates state on barrier trip and wakes up everyone.
* Called only while holding lock.
*
* 更新屏障行程状态并唤醒所有人。只在保持锁定时调用。
* 1.唤醒所有线程 2.重置count 3.generation。
*/
private void nextGeneration() {
// signal completion of last generation 上一代信号完成
trip.signalAll();
// set up next generation 建立下一代
count = parties;
generation = new Generation();
}
/**
* Sets current barrier generation as broken and wakes up everyone.
* Called only while holding lock.
*
* 将当前的屏障设置为“已破坏”,并唤醒所有人。只在保持锁定时调用。
* 默认barrier是没有损坏的。 当barrier损坏了或者有一个线程中断了,则通过breakBarrier()来终止所有的线程:
*/
private void breakBarrier() {
/**
* 在breakBarrier()中除了将broken设置为true,还会调用
* signalAll将在CyclicBarrier处于等待状态的线程全部唤醒。
* 当所有线程都已经到达barrier处(index == 0),
* 则会通过nextGeneration()进行更新换地操作
*/
generation.broken = true;
count = parties;
trip.signalAll();
}
/**
* Main barrier code, covering the various policies.
* 主要障碍代码,涵盖各种政策。
*
* await()的处理逻辑:
* 如果该线程不是到达的最后一个线程,则他会一直处于等待状态,除非发生以下情况:
* 1.最后一个线程到达,即index == 0
* 2.超出了指定时间(超时等待)
* 3.其他的某个线程中断当前线程
* 4.其他的某个线程中断另一个等待的线程
* 5.其他的某个线程在等待barrier超时
* 6.其他的某个线程在此barrier调用reset()方法。reset()方法用于将屏障重置为初始状态。
*/
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
// 获取锁
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 分代
final Generation g = generation;
// 当前generation“已损坏”,抛出BrokenBarrierException异常,
// 抛出该异常一般都是某个线程在等待某个处于“断开”状态的CyclicBarrie
if (g.broken)
// 当某个线程试图等待处于断开状态的 barrier 时,或者 barrier
// 进入断开状态而线程处于等待状态时,抛出该异常
throw new BrokenBarrierException();
// 如果线程中断,终止CyclicBarrier
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
// 进来一个线程 count - 1
int index = --count;
// count == 0 表示所有线程均已到位,触发Runnable任务 tripped 绊倒
if (index == 0) {
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
// 触发任务
if (command != null)
command.run();
ranAction = true;
// 唤醒所有等待线程,并更新generation
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out 循环直到跳闸、中断、中断或超时
for (;;) {
try {
// 如果不是超时等待,则调用Condition.await()方法等待
if (!timed)
trip.await();
else if (nanos > 0L)
// 超时等待,调用Condition.awaitNanos()方法等待
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
// We're about to finish waiting even if we had not
// been interrupted, so this interrupt is deemed to
// "belong" to subsequent execution.
// 即使我们没有被中断,我们也即将结束等待,所以这个中断被认为是“属于”后续执行。
Thread.currentThread().interrupt();
}
}
if (g.broken)
throw new BrokenBarrierException();
// generation已经更新,返回index
if (g != generation)
return index;
// “超时等待”,并且时间已到,终止CyclicBarrier,并抛出异常
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
/**
* Creates a new {@code CyclicBarrier} that will trip when the
* given number of parties (threads) are waiting upon it, and which
* will execute the given barrier action when the barrier is tripped,
* performed by the last thread entering the barrier.
*
* @param parties the number of threads that must invoke {@link #await}
* before the barrier is tripped
* @param barrierAction the command to execute when the barrier is
* tripped, or {@code null} if there is no action
* @throws IllegalArgumentException if {@code parties} is less than 1
*
* 创建一个新的 CyclicBarrier,它将在给定数量的参与者(线程)处于等待状态时启动,
* 并在启动 barrier 时执行给定的屏障操作,该操作由最后一个进入 barrier 的线程执行。
*/
public CyclicBarrierT1(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
/**
* Creates a new {@code CyclicBarrier} that will trip when the
* given number of parties (threads) are waiting upon it, and
* does not perform a predefined action when the barrier is tripped.
*
* @param parties the number of threads that must invoke {@link #await}
* before the barrier is tripped
* @throws IllegalArgumentException if {@code parties} is less than 1
*
* 创建一个新的 CyclicBarrier,它将在给定数量的参与者(线程)处于等待状态时启动,
* 但它不会在启动 barrier 时执行预定义的操作。
*/
public CyclicBarrierT1(int parties) {
this(parties, null);
}
/**
* Returns the number of parties required to trip this barrier.
*
* @return the number of parties required to trip this barrier
*/
public int getParties() {
return parties;
}
/**
* Waits until all {@linkplain #getParties parties} have invoked
* {@code await} on this barrier.
*
* <p>If the current thread is not the last to arrive then it is
* disabled for thread scheduling purposes and lies dormant until
* one of the following things happens:
* <ul>
* <li>The last thread arrives; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* one of the other waiting threads; or
* <li>Some other thread times out while waiting for barrier; or
* <li>Some other thread invokes {@link #reset} on this barrier.
* </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.
*
* <p>If the barrier is {@link #reset} while any thread is waiting,
* or if the barrier {@linkplain #isBroken is broken} when
* {@code await} is invoked, or while any thread is waiting, then
* {@link BrokenBarrierException} is thrown.
*
* <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting,
* then all other waiting threads will throw
* {@link BrokenBarrierException} and the barrier is placed in the broken
* state.
*
* <p>If the current thread is the last thread to arrive, and a
* non-null barrier action was supplied in the constructor, then the
* current thread runs the action before allowing the other threads to
* continue.
* If an exception occurs during the barrier action then that exception
* will be propagated in the current thread and the barrier is placed in
* the broken state.
*
* 如果当前线程是最后到达的线程,并且构造函数中提供了一个非空的barrier操作,那么
* current线程在允许其他线程继续之前运行该操作。如果在屏障操作期间发生异常,
* 则该异常将在当前线程中传播,并且屏障将处于中断状态。
*
* @return the arrival index of the current thread, where index
* {@code getParties() - 1} indicates the first
* to arrive and zero indicates the last to arrive
* @throws InterruptedException if the current thread was interrupted
* while waiting
* @throws BrokenBarrierException if <em>another</em> thread was
* interrupted or timed out while the current thread was
* waiting, or the barrier was reset, or the barrier was
* broken when {@code await} was called, or the barrier
* action (if present) failed due to an exception
*
* 在所有参与者都已经在此 barrier 上调用 await 方法之前,将一直等待。
* 超时控制
*/
public int await() throws InterruptedException, BrokenBarrierException {
try {
// 不超时等待
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
/**
* Waits until all {@linkplain #getParties parties} have invoked
* {@code await} on this barrier, or the specified waiting time elapses.
*
* <p>If the current thread is not the last to arrive then it is
* disabled for thread scheduling purposes and lies dormant until
* one of the following things happens:
* <ul>
* <li>The last thread arrives; or
* <li>The specified timeout elapses; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* one of the other waiting threads; or
* <li>Some other thread times out while waiting for barrier; or
* <li>Some other thread invokes {@link #reset} on this barrier.
* </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.
*
* <p>If the specified waiting time elapses then {@link TimeoutException}
* is thrown. If the time is less than or equal to zero, the
* method will not wait at all.
*
* <p>If the barrier is {@link #reset} while any thread is waiting,
* or if the barrier {@linkplain #isBroken is broken} when
* {@code await} is invoked, or while any thread is waiting, then
* {@link BrokenBarrierException} is thrown.
*
* <p>If any thread is {@linkplain Thread#interrupt interrupted} while
* waiting, then all other waiting threads will throw {@link
* BrokenBarrierException} and the barrier is placed in the broken
* state.
*
* <p>If the current thread is the last thread to arrive, and a
* non-null barrier action was supplied in the constructor, then the
* current thread runs the action before allowing the other threads to
* continue.
* If an exception occurs during the barrier action then that exception
* will be propagated in the current thread and the barrier is placed in
* the broken state.
*
* @param timeout the time to wait for the barrier
* @param unit the time unit of the timeout parameter
* @return the arrival index of the current thread, where index
* {@code getParties() - 1} indicates the first
* to arrive and zero indicates the last to arrive
* @throws InterruptedException if the current thread was interrupted
* while waiting
* @throws TimeoutException if the specified timeout elapses.
* In this case the barrier will be broken.
* @throws BrokenBarrierException if <em>another</em> thread was
* interrupted or timed out while the current thread was
* waiting, or the barrier was reset, or the barrier was broken
* when {@code await} was called, or the barrier action (if
* present) failed due to an exception
*/
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}
/**
* Queries if this barrier is in a broken state.
*
* @return {@code true} if one or more parties broke out of this
* barrier due to interruption or timeout since
* construction or the last reset, or a barrier action
* failed due to an exception; {@code false} otherwise.
*/
public boolean isBroken() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return generation.broken;
} finally {
lock.unlock();
}
}
/**
* Resets the barrier to its initial state. If any parties are
* currently waiting at the barrier, they will return with a
* {@link BrokenBarrierException}. Note that resets <em>after</em>
* a breakage has occurred for other reasons can be complicated to
* carry out; threads need to re-synchronize in some other way,
* and choose one to perform the reset. It may be preferable to
* instead create a new barrier for subsequent use.
*
* 屏障重置为初始状态。如果任何一方当前正在等待关卡,它们将返回一个
* {@link brokenbarriereexception}。注意,在</em>之后将<em>重新设置
* 由于其他原因而发生的破损可能会很复杂执行;线程需要以其他方式重新同步,
* 并选择一个执行重置。也许是更好的相反,为以后的使用创造一个新的障碍。
*
* 将屏障重置为初始状态
*/
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation 打破当代
nextGeneration(); // start a new generation 开始下一代
} finally {
lock.unlock();
}
}
/**
* Returns the number of parties currently waiting at the barrier.
* This method is primarily useful for debugging and assertions.
*
* @return the number of parties currently blocked in {@link #await}
*/
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return parties - count;
} finally {
lock.unlock();
}
}
}
以上