AQS 源码解读系列--CyclicBarrier 篇

39 篇文章 0 订阅
21 篇文章 0 订阅

循环栅栏适用的场景同计数器类似,差别在于计数器更适合某个线程等待多个线程到达某个状态(countDown)的场景,而循环栅栏更适合多个线程共同等待某个预设的状态(count == 0),到达状态后每个线程再继续执行各自的任务。这里举一个生活中的例子,比如公司举办运动会招募了10名志愿者,每个志愿者要要做什么由一个组织者 A 来进行安排,A 通知大家第二天9点在公司集合,到齐之后安排工作。于是 A 8:30来到公司等待志愿者到齐开始安排任务,此时 A 的等待就适合使用计数器。运动会上有一项田径比赛,一共有5名选手参赛,先到的选手需要等待未到的选手就位,比赛才能开始进行,此时选手之间的等待就适合使用循环栅栏。

1. CyclicBarrier()

public CyclicBarrier(int parties) {
    this(parties, null);
}
public CyclicBarrier(int parties, Runnable barrierAction) {
    if (parties <= 0) throw new IllegalArgumentException();
    this.parties = parties;
    this.count = parties;
    this.barrierCommand = barrierAction;
}

2. await()

public int await() throws InterruptedException, BrokenBarrierException {
    try {
        return dowait(false, 0L);
    } catch (TimeoutException toe) {
        throw new Error(toe); // cannot happen
    }
}

dowait()

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

		// 如果当前线程被中断过,将 barrier 的状态重置并唤醒所有等待中的线程
        if (Thread.interrupted()) {
        	// 将 barrier 的状态重置并唤醒所有当前 generation 下阻塞中的线程
            breakBarrier();
            throw new InterruptedException();
        }

        int index = --count;
        if (index == 0) {  // tripped
            boolean ranAction = false;
            try {
            	// barrierCommand 来自实例化 CyclicBarrier 时传入的任务
                final Runnable command = barrierCommand;
                if (command != null)
                    command.run();
                ranAction = true;
                // 重置 barrier 至初始状态,以便下一轮使用,这也是 CyclicBarrier 可循环使用的实现
                // 每次到达栅栏后,会产生下一代
                nextGeneration();
                return 0;
            } finally {
            	// 任务未执行成功,也会将 barrier 的状态重置并唤醒所有当前 generation 下阻塞中的线程
                if (!ranAction)
                    breakBarrier();
            }
        }

        // loop until tripped, broken, interrupted, or timed out
        for (;;) {
            try {
            	// 不需要超时判断,直接将当前线程加入等待队列,直到最后一个加入的线程执行 int index = --count; 后将计数器清零;
            	// 进而执行 nextGeneration(); 方法将所有等待队列中的线程唤醒
                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();
    }
}

breakBarrier()

private void breakBarrier() {
    generation.broken = true;
    count = parties;
    // 唤醒最后一代里等待队列中的线程
    trip.signalAll();
}

nextGeneration()

private void nextGeneration() {
    // signal completion of last generation
    // 唤醒最后一代里等待队列中的线程
    trip.signalAll();
    // set up next generation
    // 重置 barrier
    count = parties;
    generation = new Generation();
}

3. reset()

public void reset() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
    	// 中断当前的一代
        breakBarrier();   // break the current generation
        // 进入下一代
        nextGeneration(); // start a new generation
    } finally {
        lock.unlock();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值