一、CyclicBarrier是什么?
源代码的解释是:
A synchronization aid that allows a set of threads to all wait for
each other to reach a common barrier point. CyclicBarriers are
useful in programs involving a fixed sized party of threads that
must occasionally wait for each other. The barrier is called
cyclic because it can be re-used after the waiting threads
其实核心就一句话:
当线程达到初始化的数量时,才能进入到下一步的操作。
怎么理解,举个栗子:
你和你的几个朋友相约去吃饭,但是餐厅有个要求,等你的几个朋友到全了,并且满足了餐厅位子情况下,你们才能计入餐厅就餐。这里的朋友们就是各个线程,餐厅就是 CyclicBarrier。
二、CyclicBarrier源码
1、构造方法
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);
}
核心参数解释:
parties the number of threads that must invoke {@link #await} before the barrier is tripped
barrierAction the command to execute when the barrier is tripped, or {@code null} if there is no action
2、核心方法:
Waits until all {@linkplain #getParties parties} have invoked {@code await} on this barrier.
调用await方法的线程告诉CyclicBarrier自己已经到达同步点,然后当前线程被阻塞。直到parties个参与线程调用了await方法,CyclicBarrier同样提供带超时时间的await和不带超时时间的await方法:
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}
这两个方法最终都会调用dowait(boolean, long)方法,它也是CyclicBarrier的核心方法:
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()) {
//将中断的线程设置为true,并同时其他阻塞的线程这个线程中断
breakBarrier();
throw new InterruptedException();
}
//获取线程的下标
int index = --count;
//如果下标为0,说明最后一个线程调用了这个方法
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
//执行任务
if (command != null)
command.run();
//执行完成
ranAction = true;
//更新新的一代,重置count,唤醒新的线程
nextGeneration();
return 0;
} finally {
//如果执行出错,将 损坏的状态设置为true
if (!ranAction)
//将中断的线程设置为true,并同时其他阻塞的线程这个线程中断
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
//如果没有时间限制,则等待
if (!timed)
trip.await();
//否则根据设置的等待时间进行等待
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
//当前代际没有损坏
if (g == generation && ! g.broken) {
//将中断的线程设置为true,并同时其他阻塞的线程这个线程中断
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();
}
}
//如果任何线程中断了,就会调用breakBarrier
//此时就会唤醒起他线程,其他线程被唤醒时候也会抛出BrokenBarrierException异常
//表示线程又中断
if (g.broken)
throw new BrokenBarrierException();
//如果正常换代了,那么就会返回当前线程的下标
if (g != generation)
return index;
//如果超时或者时间小等于0了,那么就会报错TimeoutException,超时
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
//释放锁
lock.unlock();
}
}
三、CyclicBarrier基本使用
//3个人聚餐
final CyclicBarrier cb =new CyclicBarrier(3, new Runnable() {
public void run() {
System.out.println("人员全部到齐了,拍照留念。。。");
try {
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//线程池
ExecutorService threadPool= Executors.newCachedThreadPool();
//模拟3个用户
for (int i = 0;i < 20; i++) {
final int user =i+1;
Runnable r=new Runnable() {
public void run() {
//模拟每个人来的时间不一样
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println(user+"到达聚餐点,当前已有"+(cb.getNumberWaiting()+1)+"人达到");
//阻塞
cb.await();
if(user==1){ //打印一句
System.out.println("拍照结束,开始吃饭...");
}
Thread.sleep((long)(Math.random()*10000));
System.out.println(user+"吃完饭..准备回家.");
}catch (InterruptedException e){
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
};
threadPool.execute(r);
}
threadPool.shutdown();
}