• 简单了解CyclicBarrier


    什么是CyclicBarrier?

    CyclicBarrier是Java的一个同步类,用于协作多线程,同时也是一个共享锁

    CyclicBarrier的使用场景

    多线程一起开始

    异步线程之间互相等待

    public static void main(String[] args) throws IOException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        for (int i = 0; i < 6; i++) {
            new MyThread(cyclicBarrier).start();
        }
        System.in.read();
    }
    
    static class MyThread extends Thread {
    
        CyclicBarrier cyclicBarrier;
    
        public MyThread(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }
    
        @Override
        public void run() {
            try {
                // 获取到锁
                Thread.sleep(1000 + new Random().nextInt(3000));
                System.out.println(Thread.currentThread().getName() + "start");
                cyclicBarrier.await();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "end");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    成员变量

    // 每次计数都是一个新的Generation
    private static class Generation {
        boolean broken = false;
    }
    
    
    private final ReentrantLock lock = new ReentrantLock();
    
    
    private final Condition trip = lock.newCondition();
    
    // 到达屏障需要的总线程数
    private final int parties;
    
    // 线程数到达屏障的时候执行的方法
    private final Runnable barrierCommand;
    
    // 当前的Generation
    private Generation generation = new Generation();
    
    // 到达屏障还差多少线程数
    private int count;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    await()

    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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();
    
            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();
                }
            }
    
            // 循环直到当前线程数到达屏障、线程被中断、超时
            for (;;) {
                try {
                    // timed 表示是否采用超时机制
                    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    nextGeneration():开启下一轮循环,重置count,唤醒条件队列所有的线程
    private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();
        // set up next generation
        count = parties;
        generation = new Generation();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    breakBarrier():设置当前循环为被打断状态,重置count,唤醒条件队列所有的线程
    private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    《洛谷深入浅出基础篇》P3916 图的遍历——逆向搜索
    C语言之结构体和共用体详解
    75基于matlab的模拟退火算法优化TSP(SA-TSP),最优路径动态寻优,输出最优路径值、路径曲线、迭代曲线。
    【Method】把 arXiv论文 转换为 HTML5 网页
    【ManageEngine卓豪】局域网监控的作用
    一篇文章带你掌握性能测试工具——Jmeter
    电网数字孪生解决方案助力智慧电网体系建设
    硬件安全与机器学习的结合
    Nvidia AGX Orin MAX9296 GMSL 载板设计要点
    Carla学习笔记(二)服务器跑carla,本地运行carla-ros-bridge并用rviz显示
  • 原文地址:https://blog.csdn.net/xtrans/article/details/136723315