是什么

字面意思是“可重复使用的栅栏”或“周期性的栅栏”,总之不是用了一次就没用了的。
CyclicBarrier - 图1

怎么用

CyclicBarrier - 图2
看图我们也知道了,CyclicBarrier 的源码最重要的就是 await() 方法了。


初始化 CyclicBarrier

  1. public CyclicBarrier(int parties, Runnable barrierAction) {
  2. if (parties <= 0) throw new IllegalArgumentException();
  3. this.parties = parties;
  4. this.count = parties;
  5. this.barrierCommand = barrierAction;
  6. }
  7. /**
  8. * Creates a new {@code CyclicBarrier} that will trip when the
  9. * given number of parties (threads) are waiting upon it, and
  10. * does not perform a predefined action when the barrier is tripped.
  11. *
  12. * @param parties the number of threads that must invoke {@link #await}
  13. * before the barrier is tripped
  14. * @throws IllegalArgumentException if {@code parties} is less than 1
  15. */
  16. public CyclicBarrier(int parties) {
  17. this(parties, null);
  18. }

上面的构造函数中除了初始化 parties 和 count 以及 barrierCommand 以外,CyclicBarrier 还提前创建好了一些变量。

  1. // CyclicBarrier 的等待线程通过 barrier 的“条件”是大家都到了栅栏上
  2. private final Condition trip = lock.newCondition();
  3. private static class Generation {
  4. boolean broken = false;
  5. }
  6. private Generation generation = new Generation();

await() 函数

  1. public int await() throws InterruptedException, BrokenBarrierException {
  2. try {
  3. return dowait(false, 0L);
  4. } catch (TimeoutException toe) {
  5. throw new Error(toe); // cannot happen
  6. }
  7. }
  1. private int dowait(boolean timed, long nanos)
  2. throws InterruptedException, BrokenBarrierException,TimeoutException {
  3. final ReentrantLock lock = this.lock;
  4. lock.lock();
  5. try {
  6. final Generation g = generation;
  7. if (g.broken)
  8. throw new BrokenBarrierException();
  9. if (Thread.interrupted()) {
  10. breakBarrier();
  11. throw new InterruptedException();
  12. }
  13. int index = --count;
  14. if (index == 0) { // tripped
  15. boolean ranAction = false;
  16. try {
  17. final Runnable command = barrierCommand;
  18. if (command != null)
  19. command.run();
  20. ranAction = true;
  21. // 唤醒等待的线程,然后开启新的一代
  22. nextGeneration();
  23. return 0;
  24. } finally {
  25. if (!ranAction)
  26. breakBarrier();
  27. }
  28. }
  29. // loop until tripped, broken, interrupted, or timed out
  30. // 如果是最后一个线程调用 await,那么上面就返回了
  31. // 下面的操作是给那些不是最后一个到达栅栏的线程执行的
  32. for (;;) {
  33. try {
  34. // 如果带有超时机制,调用带超时的 Condition 的 await 方法等待,
  35. 直到最后一个线程调用 await
  36. if (!timed)
  37. trip.await();
  38. else if (nanos > 0L)
  39. nanos = trip.awaitNanos(nanos);
  40. } catch (InterruptedException ie) {
  41. if (g == generation && ! g.broken) {
  42. breakBarrier();
  43. throw ie;
  44. } else {
  45. // We're about to finish waiting even if we had not
  46. // been interrupted, so this interrupt is deemed to
  47. // "belong" to subsequent execution.
  48. Thread.currentThread().interrupt();
  49. }
  50. }
  51. if (g.broken)
  52. throw new BrokenBarrierException();
  53. if (g != generation)
  54. return index;
  55. if (timed && nanos <= 0L) {
  56. breakBarrier();
  57. throw new TimeoutException();
  58. }
  59. }
  60. } finally {
  61. lock.unlock();
  62. }
  63. }

看怎么开启新的一代:

// 开启新的一代,当最后一个线程到达栅栏上的时候,调用这个方法来唤醒其他线程,同时初始化“下一代”
private void nextGeneration() {
    // 首先,需要唤醒所有的在栅栏上等待的线程
    trip.signalAll();
    // 更新 count 的值
    count = parties;
    // 重新生成“新一代”
    generation = new Generation();
}

开启新的一代,类似于重新实例化一个 CyclicBarrier 实例

看看怎么打破一个栅栏:

private void breakBarrier() {
    // 设置状态 broken 为 true
    generation.broken = true;
    // 重置 count 为初始值 parties
    count = parties;
    // 唤醒所有已经在等待的线程
    trip.signalAll();
}


总结

在初始化 CyclicBarrier 时,会初始化线程数 count。然后每次线程 t 执行 await() 时,会把这个线程放入到条件队列里面,并且令 count - 1。当 count = 0 时,会执行一个 runnable(也是我们传入的参数) 方法,接着开启新的一代,此时会调用 signalAll() 方法唤醒在等待队列里的所有线程。