【JUC系列】循环栅栏CyclicBarrier实现原理

简单示例

public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cb = new CyclicBarrier(2, () -> {
            System.out.println("即将打破屏障");
        });

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "开始运行");
                try {
                    cb.await();
                    System.out.println(Thread.currentThread().getName() + "已经穿越了第1个屏障");
                    cb.await();
                    System.out.println(Thread.currentThread().getName() + "已经穿越了第2个屏障");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

运行结果:

Thread-0开始运行
Thread-1开始运行
即将打破屏障
Thread-1已经穿越了第1个屏障
Thread-0已经穿越了第1个屏障
即将打破屏障
Thread-0已经穿越了第2个屏障
Thread-1已经穿越了第2个屏障

在这里插入图片描述

源码分析

构造方法

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

await()

  1. 将计数器减1,如果计数器不等于0,执行 trip.await();,进行阻塞;如果计数器等于0,执行command,唤醒线程。
    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();
        }
    }

CyclicBarrier#nextGeneration,唤醒阻塞线程。

private void nextGeneration() {
    // signal completion of last generation
    trip.signalAll();
    // set up next generation
    count = parties;
    generation = new Generation();
}

CountDownLatch和CyclicBarrier的区别

CountDownLatch,是一个线程或多个线程等待另外多个线程执行完毕之后才执行。内部维护一个计数器,每个线程调用一次countDown后,计数器减1,计数器减为0后,会唤醒因调用await()而阻塞的线程。

CyclicBarrier,多个线程互相等待,直到所有的线程都达到屏障点,才可以一起接着执行。同样可以理解为内部有一个可重置的计数器,每个线程调用await()后,计数器减1,若计数器的值不为0,将会阻塞该线程。当最后一个线程调用await()后,计数器为0,将会唤醒所有阻塞的线程,并开启下一代,重置此计数器的值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值