什么是CyclicBarrier?

CyclicBarrier是Java的一个同步类,用于协作多线程,同时也是一个共享锁

CyclicBarrier的使用场景

多线程一起开始

异步线程之间互相等待

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static void main(String[] args) throws IOException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
for (int i = 0; i < 6; i++) {
new MyThread(cyclicBarrier).start();
}
System.in.read();
}

static class MyThread extends Thread {

CyclicBarrier cyclicBarrier;

public MyThread(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}

@Override
public void run() {
try {
// 获取到锁
Thread.sleep(1000 + new Random().nextInt(3000));
System.out.println(Thread.currentThread().getName() + "start");
cyclicBarrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + "end");
}
}

CyclicBarrier源码解析

构造器

1
2
3
4
5
6
7
8
9
10
public CyclicBarrier(int parties) {
this(parties, null);
}

public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}

成员变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 每次计数都是一个新的Generation
private static class Generation {
boolean broken = false;
}


private final ReentrantLock lock = new ReentrantLock();


private final Condition trip = lock.newCondition();

// 到达屏障需要的总线程数
private final int parties;

// 线程数到达屏障的时候执行的方法
private final Runnable barrierCommand;

// 当前的Generation
private Generation generation = new Generation();

// 到达屏障还差多少线程数
private int count;

await()

1
2
3
4
5
6
7
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}

dowait()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
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();
}

int index = --count;
// 当前线程数到达屏障
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
// 执行方法
if (command != null)
command.run();
ranAction = true;
// 唤醒条件队列所有线程,并且更新屏障
nextGeneration();
return 0;
} finally {
// 将当前屏障生成设置为已损坏并唤醒条件队列所有线程
if (!ranAction)
breakBarrier();
}
}

// 循环直到当前线程数到达屏障、线程被中断、超时
for (;;) {
try {
// timed 表示是否采用超时机制
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();
}
}

nextGeneration():开启下一轮循环,重置count,唤醒条件队列所有的线程

1
2
3
4
5
6
7
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}

breakBarrier():设置当前循环为被打断状态,重置count,唤醒条件队列所有的线程

1
2
3
4
5
private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}