使用场景

同步屏障,作用和countdownlatch功能类似

源码思路

相当于countdownlatch的state减到0,执行完屏障的逻辑后,会重置为初始值,就又可以继续使用了。
但是它自己写了锁标识,有两个锁标识,额外的一个就是为了重置时使用。

手动重置屏障变量

  1. public void reset() {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. breakBarrier(); // break the current generation
  6. nextGeneration(); // start a new generation
  7. } finally {
  8. lock.unlock();
  9. }
  10. }

重置变量方法

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

内部使用ReentrantLock加锁,Condition作为等待队列,自定义的屏障变量

  1. public class CyclicBarrier {
  2. /**
  3. * Each use of the barrier is represented as a generation instance.
  4. * The generation changes whenever the barrier is tripped, or
  5. * is reset. There can be many generations associated with threads
  6. * using the barrier - due to the non-deterministic way the lock
  7. * may be allocated to waiting threads - but only one of these
  8. * can be active at a time (the one to which {@code count} applies)
  9. * and all the rest are either broken or tripped.
  10. * There need not be an active generation if there has been a break
  11. * but no subsequent reset.
  12. */
  13. private static class Generation {
  14. boolean broken = false;
  15. }
  16. /** The lock for guarding barrier entry */
  17. private final ReentrantLock lock = new ReentrantLock();
  18. /** Condition to wait on until tripped */
  19. private final Condition trip = lock.newCondition();
  20. /** The number of parties */
  21. private final int parties;
  22. /* The command to run when tripped */
  23. private final Runnable barrierCommand;
  24. /** The current generation */
  25. private Generation generation = new Generation();