CycleBarrier回环屏障源码解析

CyclicBarrier是回环屏障的意思,它可以让一组线程全部达到一个状态后再全部同时执行,之所以叫回环是因为当所有线程执行完毕,可以重置CyclicBarrier状态,进行复用,这也是它与CountDownLatch的主要区别,下面介绍一个案例:

public class CyclicBarrierTest {

        public static void main(String[] args) {
            int N = 4;
            CyclicBarrier barrier  = new CyclicBarrier(N);
            for(int i=0;i

上面的例子说明多个线程之间是相互等待的,假如计数器为N,那么随后调用await()方法的N-1个线程都会因为达到屏障点而被阻塞,当第N个线程调用await()方法后,计数器的值为0,这时第N个线程会通知唤醒前面的N-1个线程。下面的案例证明CyclicBarrier的可复用性:

public class CyclicBarrierTest {
    private static CyclicBarrier cyclicBarrier=new CyclicBarrier(2);

    public static void main(String[] args) {
        ExecutorService executorService= Executors.newFixedThreadPool(2);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread()+" step1");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step2");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step3");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread()+" step1");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step2");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step3");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        executorService.shutdown();
    }
}

运行结果:
Thread[pool-1-thread-1,5,main] step1
Thread[pool-1-thread-2,5,main] step1
Thread[pool-1-thread-2,5,main] step2
Thread[pool-1-thread-1,5,main] step2
Thread[pool-1-thread-1,5,main] step3
Thread[pool-1-thread-2,5,main] step3

为了了解CyclicBarrier的原理,我们来看一下该类的架构设计:

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;   //通过维护parties和count两个变量来进行CyclicBarrier的复用

    
    private void nextGeneration() {
        // 唤醒条件队列所有线程
        trip.signalAll();
        // 将parties的值传递给count,进行复用
        count = parties;
        generation = new Generation();
    }

    
    private void breakBarrier() {
        //记录屏障是否被打破
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }

    //当线程调用dawait方法后,会获取独占锁,其它竞争线程被阻塞
    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();
            }
            //获取锁的线程对count进行自减操作
            int index = --count;
            //满足条件则知所有线程都到达了屏障点,开始执行传递的任务
            if (index == 0) {  
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    //执行传递的任务
                    if (command != null)
                        command.run();
                    ranAction = true;
                    //激活其它被阻塞的线程,并重置CyclicBarrier的计数
                    nextGeneration();
                    return 0;
                } finally {
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // 经典的无限自传循环,直到满足条件
            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();
        }
    }

    //初始化屏障计数
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        将parties的值传递给count,进行复用重置
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

    //调用cyclicBarrier的构造方法
    public CyclicBarrier(int parties) {
        this(parties, null);
    }

   //调用dowait()方法
    public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
                //true说明了设置了超时时间
        return dowait(true, unit.toNanos(timeout));
    }
    
    
}

由上述源代码可知,CyclicBarrier基于独占锁实现,本质还是之前讲述过的AQS。CyclicBarrier维护parties和count两个变量,初始化时,count等于parties,每当有线程调用await()方法时,count值减去1,当count值为0时表示所有线程都达到了屏障点,维护两个变量是为了进行CyclicBarrier的复用,当count为0时,会将parties的值传给count,这个过程是在构造CyclicBarrier传递的。在变量generation内部维护一个变量broken,用来记录变量是否被打破。

你可能感兴趣的:(java多线程)