CyclicBarrier
是一个同步辅助类,允许一组线程互相等待直到到达一个公共屏障点(common barrier),当涉及到一组固定大小必须相互等待的线程是非常有用的。
他之所以称为cyclic
是因为当线程释放,CyclicBarrier
可以被重复使用。
主要属性
1 | public class CyclicBarrier { |
构造器
1 | public CyclicBarrier(int parties) { |
其构造其有两个参数:
parties
:表示参与的线程数barriesAction
:当达到给定数量的线程处于等待状态 启动barrier时执行给定的屏障操作,此操作由最后进入barrier的线程执行。
等待 await
1 | public int await() throws InterruptedException, BrokenBarrierException { |
await()
最终调用的是超时版本的dowait1
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
67private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Generation g = generation;
//当前generation已损坏 则抛出BrokenBarrierException异常
if (g.broken)
throw new BrokenBarrierException();
//线程中断则终止barrier
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
//进来一个线程 count自减一
int index = --count;
if (index == 0) { // index==0 表示线程都到位 则执行Runnable任务
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
if (command != null)
command.run();//出发屏障任务
ranAction = true;
nextGeneration();//唤醒所有等待任务 并更新generation
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
if (!timed)//非超时等待 调用Condition.await()一直等待
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)//generation已更新 返回index
return index;
if (timed && nanos <= 0L) {//等待超时 终止barrier 并抛出异常
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
换代
当线程都到位,并且最后一个进入的线程成功执行了屏障任务,则调用nextGeneration()
方法进行换代 并唤醒所有线程1
2
3
4
5
6
7private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}
终止Barrier
当线程被中断或线程等待超时 则调用breakBarrier()
方法终止Barrier1
2
3
4
5private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}