淘先锋技术网

首页 1 2 3 4 5 6 7

栅栏不同于倒计时器的一点是倒计时器是一个或N个线程等待其他线程调用countdown()到指定次数后再继续执行,而栅栏是N个线程之间互相等待,当调用await()到达指定次数后就会唤醒所有等待线程,同时还可以在到达指定数量时触发一个定制的动作(Runnable,由最后一个调用await()方法并唤醒所有线程的那个线程执行)。另外栅栏是可以循环使用的。

栅栏的实现方式是独占锁+Condition条件来实现的。

先看个Demo:

package com.pzx.test005;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
    static CyclicBarrier cyclicBarrier;

    public static void main(String[] args) {
        cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " do something...");
            }
        });

        ThreadA threadA = new ThreadA();
        for(int i=0; i<5; i++) {
            Thread thread = new Thread(threadA, "t"+i);
            thread.start();
        }
    }

    static class ThreadA implements Runnable{
        @Override
        public void run() {
            System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " begin work...");
            try {
                System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " await...");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

            System.out.println(sdf.format(new Date()) + Thread.currentThread().getName() + " continue work...");
        }
    }
}

执行结果:

2018-09-11 13:54:27 t0 begin work...
2018-09-11 13:54:27 t0 await...
2018-09-11 13:54:27 t4 begin work...
2018-09-11 13:54:27 t4 await...
2018-09-11 13:54:27 t1 begin work...
2018-09-11 13:54:27 t1 await...
2018-09-11 13:54:27 t3 begin work...
2018-09-11 13:54:27 t3 await...
2018-09-11 13:54:27 t2 begin work...
2018-09-11 13:54:27 t2 await...
2018-09-11 13:54:27 t2 do something...
2018-09-11 13:54:27 t2 continue work...
2018-09-11 13:54:27 t0 continue work...
2018-09-11 13:54:27 t4 continue work...
2018-09-11 13:54:27 t1 continue work...
2018-09-11 13:54:27 t3 continue work...

public class CyclicBarrier {
    // 内部类,因为栅栏可以循环使用,每使用一次都是一代,这个类可判断是否处于同一代
    private static class Generation {
        boolean broken = false;
    }
    // 可重入锁
    private final ReentrantLock lock = new ReentrantLock();
    // 创建Condition,释放所有线程的条件
    private final Condition trip = lock.newCondition();
    // 栅栏中的线程总个数
    private final int parties;
    // 当要释放时触发的动作
    private final Runnable barrierCommand;
    // 创建当前代
    private Generation generation = new Generation();
    // 还剩多少线程可以达到条件,进来一个线程就-1
    private int count;
    // 构造函数
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = 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();
            }
            // 一个线程进来后,count-1
            int index = --count;
            // 如果count已经减到0了,说明是时候唤醒所有线程往下运行了
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    // 如果构造函数中有传入Runnable对象,就在唤醒所有线程之前执行Runnable里面
                    // 的run方法
                    if (command != null)
                        command.run();
                    ranAction = true;
                    // 重置参数,进入下一代
                    nextGeneration();
                    return 0;
                } finally {
                    // 如果上述唤醒的过程(command.run();)发生了什么意外导致异常了,就破坏当前 
                    // 的栅栏
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // loop until tripped, broken, interrupted, or timed out
            // 循环,一直到要被唤醒了,或者栅栏被破坏了,或者线程被中断了,或者超时了
            for (;;) {
                try {
                    // 如果没有设置超时参数,就执行await(即当前线程阻塞,释放上面的独占锁,
                    // 等待被唤醒)
                    if (!timed)
                        trip.await();
                    // 如果设置了超时参数,就阻塞超时参数那么长的时间
                    else if (nanos > 0L)
                        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();
                // 如果在这个执行过程中换代了就返回index(即当前count-1值)
                if (g != generation)
                    return index;
                // 输入的超时参数的合法性判断,不合法就破坏当前代的栅栏
                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }
  
    // 开启下一代
    private void nextGeneration() {
        // 唤醒所有的等待的线程,相当于把栅栏拉开
        trip.signalAll();
        // 重置count和generation 
        count = parties;
        generation = new Generation();
    }
    // 破坏栅栏
    private void breakBarrier() {
        // 当前代被破坏置true,重置count,唤醒所有的线程
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }
    // 重置栅栏
    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }