java 并发工具包 -栅栏 CyclicBarrier

简介

CyclicBarrier 顾名思义,栅栏;对于我们并发场景来说,就是一个所有线程必须等待的一个栅栏,直到所有线程都到达这里,然后所有线程才可以继续做其他事情!

参数

//栅栏是否被打破
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;

    private Generation generation = new Generation();
    //剩余等待的线程数
    private int count;

源码分析

public class CyclicBarrier {
  //静态内部类,只有一个参数标识
    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;

    private Generation generation = new Generation();

  //剩余线程数量
    private int count;

    /**
     * 状态重置
     */
    private void nextGeneration() {
        // 唤醒所有线程
        trip.signalAll();
        // 重置
        count = parties;
        generation = new Generation();
    }

    /**
     * 标记当前打破状态为true,并且唤醒全部线程
     */
    private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }

    /**
     * 栅栏主要方法 是否需要过期时间、过期时间
     */
    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();
            }
            //剩余线程个数-1
            int index = --count;
            //当为剩余线程为0时
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    //不为nul就执行
                    if (command != null)
                        command.run();
                    ranAction = true;
                    //重置 等待下一个任务
                    nextGeneration();
                    return 0;
                } finally {
                    //如果执行异常,则打破之
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // 一直循环直到所有线程到达、打断、超时
            for (;;) {
                try {
                //如果不需要超时,则直接阻塞
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)//需要则阻塞至nanos时间
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    //被打断 则直接释放已阻塞线程  

                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {

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

 //初始化
    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);
    }


    public int getParties() {
        return parties;
    }

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

 //是否打破
    public boolean isBroken() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return generation.broken;
        } finally {
            lock.unlock();
        }
    }

  //重置
    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }

 //正在等待的线程个数
    public int getNumberWaiting() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return parties - count;
        } finally {
            lock.unlock();
        }
    }
}

CyclicBarrier 其实没有多少代码,主要是通过Condition的 await、awaitNanos、signalAll实现

`

总结

当需要所有的子任务都完成时,才执行主任务,这时既可以选择使用CyclicBarrier。
举个例子:学校举行秋游,老师要等所有的学生到齐之后才能出发。
那么这里的线程就是学生,栅栏的条件就是所有学生到齐,栅栏的Runnable就是出发!

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
            @Override
            public void run() {
                System.out.println("出发去秋游喽!");
            }
        });

        new Thread(new CyclicBarrierRun(cyclicBarrier), "学生1").start();
        Thread.sleep(1000);
        new Thread(new CyclicBarrierRun(cyclicBarrier), "学生2").start();
        Thread.sleep(1000);
        new Thread(new CyclicBarrierRun(cyclicBarrier), "学生3").start();
    }

    public static class CyclicBarrierRun implements Runnable {
        private CyclicBarrier cyclicBarrier;

        public CyclicBarrierRun(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "到达!");

            try {
                this.cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "准备出发!");

        }

    }

你可能感兴趣的:(并发-java)