今天来介绍一下并发库中的另一个工具——障碍物(CyclicBarrier)
/**
* 基于ReentrantLock实现,常用方法如下:
* 1. CyclicBarrier(3): 设置计数
* 2. await(): 计数减一
* 2.1 如果计数大于0,释放当前线程持有的锁,唤醒下一个等待线程(如果没有执行过2.2,此处应该没有线程可被唤醒),挂起当前线程(condition.await())
* 2.2 如果计数等于0,唤醒下一个线程(2.1中等待的线程),继续执行到下一个集结点(重新开始计数)
*
*/
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CyclicBarrier cb = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
service.execute(() -> {
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("thread: " + Thread.currentThread().getName() + "到达集合点1,已有" + (cb.getNumberWaiting()+1) + "人到达");
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("thread: " + Thread.currentThread().getName() + "到达集合点2,已有" + (cb.getNumberWaiting()+1) + "人到达");
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("thread: " + Thread.currentThread().getName() + "到达集合点3,已有" + (cb.getNumberWaiting()+1) + "人到达");
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
});
}
service.shutdown();
}
}
await
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
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();
}
}
// 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) {
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();
}
}
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}