CyclicBarrier应用场景
实现了若干个线程都到达了某一个具体的点,这些线程再同时开始执行。
- 没有主次之分
- 当所有线程都到达屏障之后,所有的线程开始执行
CyclicBarrier相对于CountDownLatch最重要的一点:
CyclicBarrier可以重复使用。
package com.learn.thread.cyclicbarrier;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
System.out.println("--------------");
});
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
new Thread(() -> {
try {
Thread.sleep((long) (Math.random() * 2000));
int randomInt = new Random(500).nextInt();
System.out.println("hello " + randomInt);
cyclicBarrier.await();
System.out.println("world " + randomInt);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
}
源码分析
构造方法
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
// 参与方的数量
this.parties = parties;
// 计数器的个数
this.count = parties;
this.barrierCommand = barrierAction;
}
public CyclicBarrier(int parties) {
this(parties, null);
}
/**
* 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;
generation:每一次CyclicBarrier的屏障被冲破或者重置,Generation 就恢复到最初的状态,进入下一个分代当中。
private static class Generation {
boolean broken = false;
}
await()方法
等到所有各方都在此障碍上调用await。
如果当前线程不是最后到达的线程,则出于线程调度目的将其禁用,并使其处于休眠状态,直到发生以下情况之一:
- 最后一个线程抵达
- 其他线程终断当前线程
- 其他线程终断等待中的线程
- 当等待barrier的时候其他线程超时
- 其他线程在这个barrier上执行reset方法
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
/**
* Main barrier code, covering the various policies.
*/
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
// 获取到ReentrantLock锁
final ReentrantLock lock = this.lock;
// 加锁
lock.lock();
try {
final Generation g = generation;
if (g.broken)
throw new BrokenBarrierException();
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
// 计数器-1,已经加锁,线程安全
int index = --count;
// 所有的线程都到达屏障
if (index == 0) { // tripped
boolean ranAction = false;
// 执行Runnable
try {
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
// 开启下一个分代
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)
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();
}
}
/**
* 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 = parties;
generation = new Generation();
}
CyclicBarrier的底层执行流程
- 初始化CyclicBarrier中的各种成员变量,包括parties、count以及Runnable(可选)。
- 当调用await方法时,底层会检查计数器是否已经归零,如果是,那么就首先执行可选的Runable,接下来开始下一个generation。
- 在一个分代中,将会重置count值为parties,并且创建新的Generation实例。
- 同时会调用Condition的signalAll方法,唤醒所有在屏障前面等待的线程,让其开始继续执行。
- 如果计数器没有归零,那么当前的调用线程将会通过Condition的await方法,在屏障前进行等待。
- 以上所有执行流程均在lock锁的控制范围内,不会出现并发情况。