【J.U.C-synchronizer】同步器框架——CyclicBarrier循环栅栏

CyclicBarrier

cyclicBarrier是一个循环栅栏,当线程达到栅栏时被阻塞,直到到达栅栏的线程数满足指定数量要求时,栅栏才会打开放行。

使用Demo

public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Thread() {
            public void run() {
                System.out.println("达到栅栏线程已满足数量");
            }
        });
        
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(3000);
                    System.out.println("线程" + Thread.currentThread().getName() + "到达栅栏");
                    cyclicBarrier.await();
                     System.out.println("线程" + Thread.currentThread().getName() + "继续执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

存储结构与构造函数

 /** The lock for guarding barrier entry */
    private final ReentrantLock lock = new ReentrantLock();
    /** Condition to wait on until tripped */
    private final Condition trip = lock.newCondition();
    /** The number of parties */
    private final int parties;
    /* The command to run when tripped */
    private final Runnable barrierCommand;
    /** The current generation */
    private Generation generation = new Generation();

    /**
     * Number of parties still waiting. Counts down from parties to 0
     * on each generation.  It is reset to parties on each new
     * generation or when broken.
     */
    private int count;
  • parties:栅栏开启需要到达的线程数
  • count:剩余未到达的线程数
  • barrierCommand:最后一个线程到达后需要执行的任务
  • 内部类Generation,因为CyclicBarrier 是可以循环复用的,所以CyclicBarrier 的每一轮任务都需要对应一个generation 对象,内部有个broken字段,用来标识当前轮次的CyclicBarrier 是否已经损坏:
private static class Generation {
        boolean broken = false;
    }

构造函数有两个:

	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);
    }

核心方法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();
        }
    }
  1. 首先获取lock,并加锁;
  2. 判断栅栏是否已被损坏,或者当前线程被中断,如果是,则抛出异常;
  3. 获取count,如果count=0
    • 执行我们自定义的线程逻辑barrierCommand
    • 执行任务成功,nextGeneration,唤醒所有等待线程,并进行下一轮等待
    • 执行任务失败,breakBarrier,破坏栅栏,唤醒所有等待线程
  4. count!= 0,不满足条件,进入自旋
    • 如果不需要限时,trip.await,直接在Condition对象上等待
    • 需要限时,则判断超时或被中断,决定是否破坏栅栏

nextGeneration进入下一轮

private void nextGeneration() {
    // signal completion of last generation
    trip.signalAll();
    // set up next generation
    count = parties;
    
    generation = new Generation();
}
 
  1. 唤醒所有线程
  2. 恢复正在等待进入屏障的线程数量
  3. 重新生成generation

breakBarrier破坏栅栏

private void breakBarrier() {
    generation.broken = true;
    count = parties;
    trip.signalAll();
}
  1. 设置状态
  2. 恢复正在等待进入屏障的线程数量
  3. 唤醒所有线程

总结

  • CyclicBarrier并没有直接实现AQS的接口,而是使用了ReentrantLock和Condition。
  • 与CountDownLatch对比:
    • CyclicBarrier是加计数,而CountDownLatch是减计数;
    • CyclicBarrier可重复使用,而CountDownLatch是一次性不可恢复;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值