CyclicBarrier 源码分析

一 代码用法  

  本质是一个重入锁加condition完成的

  每个线程逻辑中调用await,对一个公共变量count进行减一,然后判断count是否为0.如果不为零,调用condition的await方法,阻塞住。直到最后那个线程会把count减一,此时

判断已经减到了0.此时就会调用condition的signalAll,特别注意signalAll只是把condition里的Node都放回到阻塞队列里。

public class CyclicBarrierDemo {

    static class TaskThread extends Thread {
        
        CyclicBarrier barrier;
        
        public TaskThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }
        
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println(getName() + " 到达栅栏 A");
                barrier.await();
                System.out.println(getName() + " 冲破栅栏 A");
                
                Thread.sleep(2000);
                System.out.println(getName() + " 到达栅栏 B");
                barrier.await();
                System.out.println(getName() + " 冲破栅栏 B");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        int threadNum = 5;
        CyclicBarrier barrier = new CyclicBarrier(threadNum, new Runnable() {
            
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " 完成最后任务");
            }
        });
        
        for(int i = 0; i < threadNum; i++) {
            new TaskThread(barrier).start();
        }
    }
    
}

与CountDownLatch不同的是,CyclicBarrier是线程之间的彼此等待,线程实现逻辑在什么地方调用await就在那个地方等待全部的代码走到那里

二 源码概览

public class CyclicBarrier {
    /**
     * Each use of the barrier is represented as a generation instance.
     * The generation changes whenever the barrier is tripped, or
     * is reset. There can be many generations associated with threads
     * using the barrier - due to the non-deterministic way the lock
     * may be allocated to waiting threads - but only one of these
     * can be active at a time (the one to which {@code count} applies)
     * and all the rest are either broken or tripped.
     * There need not be an active generation if there has been a break
     * but no subsequent reset.
     */
    private static class Generation {
        boolean broken = false;
    }

    /** The lock for guarding barrier entry */
    private final ReentrantLock lock = new ReentrantLock();
    /** Condition to wait on until tripped */
    private final Condition trip = lock.newCondition();
    /** The number of parties */
    private final int parties;
    /* The command to run when tripped */
    private final Runnable barrierCommand;
    /** The current generation */
    private Generation generation = new Generation();

    /**
     * Number of parties still waiting. Counts down from parties to 0
     * on each generation.  It is reset to parties on each new
     * generation or when broken.
     */
    private int count;

  看得出来,和CountDownLatch不同, CyclicBarrier 是直接使用了   ReentrantLock  和  Condition  来实现的

  

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

  parties表示有几个线程需要同步, Runnable barrierAction 是最后一个线程完成后要做的动作。

三 await源码分析

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 //如果已经减到了0 那么说明所有的线程都到达了指定地点,那么就可以唤醒继续了
                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();//调用condition的await,当前线程包成waitNode进入条件队列并阻塞起来
                    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();//因为每一个进入条件队列的Node最终都会,再次进入同步队列中再次加入到获取锁的逻辑,所以最后都要unlock
        }
    }

四   nextGeneration 源码分析

private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();//释放全部在条件队列中的阻塞,线程重新进入同步队列,从上面的代码能看出来,拿到锁后什么都不干,就会unlock所以,所有线程到达了barrier后很快就会往下走
        // set up next generation
        count = parties;//重新给count赋值,虽说CyclicBarrier可以重用,但是这个count是不能修改的 private final int parties;
        generation = new Generation();
    }

五 总结

CyclicBarrier 和 CountDownLatch 相比有这么个特点,就是它只提供了一个await方法,线程之间彼此等待

posted on 2020-11-24 18:14  MaXianZhe  阅读(122)  评论(0编辑  收藏  举报

导航