CycilcBarrier

CycilcBarrier的应用场景为多个线程进行不同阶段的任务,当所有线程到达await()后指定的任务才会被执行。

CycilcBarrier的结构

  CycilcBarrier内部包含几个属性

public class CyclicBarrier {

    /** 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;
}

构造函数

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

  parties指定线程数量, barrierAction为线程进入屏障后的任务。

核心函数await和doawait

	public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }
	public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

  await内部调用了doawait,所以核心还是落在了doawait上

	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) {  // 等待线程数为0,唤醒所有线程准备进入下一代
                boolean ranAction = false; // 运行标识
                try {
                    final Runnable command = barrierCommand;
                    if (command != null) // 执行runnable
                        command.run();
                    ranAction = true;
                    nextGeneration(); // 唤醒所有线程,进入下一代,把count值复原
                    return 0;
                } finally {
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) { //上面的if没执行说明有线程还没完成,阻塞
                try {
                    if (!timed)
                        trip.await(); // await阻塞自己释放锁,其他线程可以在lock.lock()获取到锁
                    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();
        }
    }

核心函数 nextGeneration

	private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll(); // 唤醒条件队列上的所有线程
        // set up next generation
        count = parties; // 复原count值
        generation = new Generation(); // 进入下一代
    }

  trip是AQS中的ConditionObject对象,signalAll()唤醒阻塞在该条件上的所有线程

		public final void signalAll() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignalAll(first); // 从头结点唤醒所有线程
        }
		private void doSignalAll(Node first) {
            lastWaiter = firstWaiter = null;
            do {
                Node next = first.nextWaiter;
                first.nextWaiter = null;
                transferForSignal(first); // 将每个线程放到阻塞队列中
                first = next;
            } while (first != null);
        }


        final boolean transferForSignal(Node node) {
        
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        Node p = enq(node);
        int ws = p.waitStatus;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }
    
    
    private Node enq(final Node node) {
        for (;;) { // 自旋将节点入队
            Node t = tail;
            if (t == null) { // 尾结点为空,初始化队列
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else { // 尾结点不为空,说明队列已经初始化过,直接加入
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

breakBarrier函数

  breakBarrier函数作用是设置当前代的broken为true,说明屏障在当前代被破坏,将count复原并将所有条件队列上的线程唤醒。

	private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }

参考资料:《Java并发实现原理:JDK源码剖析》
https://www.pdai.tech/md/java/thread/java-thread-x-juc-tool-cyclicbarrier.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值