CyclicBarrier源码解析
作者:互联网
CyclicBarrier的实现比较简单,是基于ReentrantLock来实现的
应用场景
一组线程在某个节点同步,再继续执行
public class CyclicBarrierTest1 {
private CyclicBarrier barrier = new CyclicBarrier(30);
public CyclicBarrier getBarrier() {
return barrier;
}
public static void main(String[] args) {
CyclicBarrierTest1 test = new CyclicBarrierTest1();
List<Thread> threadList = new ArrayList<>();
for (int i = 0; i < 30; i++) {
Thread thread = new A(i, test.getBarrier());
threadList.add(thread);
}
for (Thread thread : threadList) {
thread.start();
}
System.out.println("主线程结束");
}
}
class A extends Thread {
private static Random random = new Random();
private int i;
private CyclicBarrier barrier;
public A(int i, CyclicBarrier barrier) {
this.i = i;
this.barrier = barrier;
}
@Override
public void run() {
long time = random.nextInt(10) * 1000L;
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.i + "号子线程睡眠:" + time);
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("所有线程睡眠完毕");
}
}
CyclicBarrier构造函数
/**
* 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
*/
public CyclicBarrier(int parties) {
this(parties, null);
}
调用了2个参数的构造函数,第二个参数为null
/**
* 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
*/
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
初始化parties、count、barrierCommand参数
- parties 表示有多少个线程需要进行同步
- count 表示剩余多少线程在休眠状态
- barrierCommand 是当count为0的时候将触发的运行逻辑
await
/**
* 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.
*
* @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
*/
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
核心逻辑 dowait
/**
* Main barrier code, covering the various policies.
*/
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
//加锁
lock.lock();
try {
final Generation g = generation;
//判断有无broken
if (g.broken)
throw new BrokenBarrierException();
//判断有无中断
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
//count - 1
int index = --count;
if (index == 0) { // tripped
//如果index为0,触发以下逻辑
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
//barrierCommand 如果不为空 则运行其逻辑
if (command != null)
command.run();
ranAction = true;
//唤醒所有休眠的线程并重置barrier
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
if (!timed)
//不带等待时间的休眠
trip.await();
else if (nanos > 0L)
//休眠nanos纳秒
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();
if (g != generation)
return index;
//休眠时间超时了
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
nextGeneration
/**
* Updates state on barrier trip and wakes up everyone.
* Called only while holding lock.
*/
private void nextGeneration() {
// signal completion of last generation
//唤醒其他阻塞的线程
trip.signalAll();
// set up next generation
//重置count和generation进行下次使用
count = parties;
generation = new Generation();
}
图解
画了张图理一下CyclicBarrier#await的基本流程
标签:CyclicBarrier,barrier,thread,waiting,源码,parties,new,解析 来源: https://www.cnblogs.com/lomoye/p/12737312.html