CyclicBarrier

public class CyclicBarrier {
    /**
     * 每一次使用CyclicBarrier可以当成Generation的实例
     */
    private static class Generation {
        boolean broken = false;
    }

    //可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    //条件队列
    private final Condition trip = lock.newCondition();

    //参与线程数量
    private final int parties;

    //最后一个线程进入barrier执行的操作
    private final Runnable barrierCommand;

    //当前代
    private Generation generation = new Generation();

    //正在等待进入barrier的线程数量
    private int count;

    //在所有线程进入barrier后会被调用,生成下一个版本,所有线程又可以重新进入到屏障中
    private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();//唤醒所有等待线程
        // set up next generation
        count = parties;//恢复正在等待进入barrier线程数量
        generation = new Generation();//生成下一代
    }

    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;
            //barrier被破坏,抛出异常
            if (g.broken)
                throw new BrokenBarrierException();
            //线程被中断
            if (Thread.interrupted()) {
                breakBarrier();//损坏barrier,唤醒所有线程,只有拥有锁的时候才会调用
                throw new InterruptedException();
            }
            //减少正在等待进入barrier线程数量
            int index = --count;
            if (index == 0) {  //正在等待进入barrier线程数量为0,当前线程为最后一个进入barrier
                //运行动作标识
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    //最后一个进入barrier线程执行操作
                    if (command != null)
                        command.run();
                    ranAction = true;
                    //进入下一代
                    nextGeneration();
                    return 0;
                } finally {
                    if (!ranAction)//没有运行的动作,最后一个线程运行出现异常
                        breakBarrier();//损坏barrier,唤醒所有线程
                }
            }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) {
                try {
                    //没有设置等待时间
                    if (!timed)
                        trip.await();//在条件队列上等待
                    else if (nanos > 0L)//设置了等待时间 > 0
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    //等于当前代且barrier没有被损坏
                    if (g == generation && ! g.broken) {
                        breakBarrier();//损坏barrier唤醒所有线程
                        throw ie;
                    } else {//不等于当前代或者barrier被损坏
                        // 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();
        }
    }

    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(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

    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();
        }
    }
}
public class Main {

    static class Ruuner implements Runnable {

        private CyclicBarrier barrier;
        private String name;

        public Ruuner(String name, CyclicBarrier barrier) {
            this.name = name;
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(100 * (new Random()).nextInt(100));
                System.out.println(name + "准备好了.");
                barrier.await();
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            } catch (BrokenBarrierException bbe) {
                bbe.printStackTrace();
            }
            System.out.println(name + "出发.");
        }
    }

    public static void main(String[] arg) {
        CyclicBarrier barrier = new CyclicBarrier(3);
        Thread t1 = new Thread(new Ruuner("1号",barrier));
        Thread t2 = new Thread(new Ruuner("2号",barrier));
        Thread t3 = new Thread(new Ruuner("3号",barrier));
        t1.start();
        t2.start();
        t3.start();
        /*Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {

        }
        scan.close();*/
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值