Java concurrent包下的并发开发辅助类(二)CyclicBarrier

直接上测试代码:

public class CyclicBarrierSample {

    public static void main(String[] args) {

        long start = new Date().getTime();

        CyclicBarrier cyclicBarrier = new CyclicBarrier(4,
                () -> System.out.println("barrierAction :" + (new Date().getTime() - start)));

        for (int i = 0; i < 4; i++) {
            CyclicBarrierThread cyclicBarrierThread = new CyclicBarrierThread("A" + i, cyclicBarrier);
            cyclicBarrierThread.start();
        }
    }


}

class CyclicBarrierThread extends Thread {
    CyclicBarrier cyclicBarrier;

    CyclicBarrierThread(String name, CyclicBarrier cyclicBarrier) {
        super(name);
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            Random random = new Random();
            int time = random.nextInt(10) * 1000;

            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(getName() + " arrive " + time);

            long arrive = new Date().getTime();

            cyclicBarrier.await();

            long exit = new Date().getTime();

            System.out.println(getName() + " exit  wait:" + (exit - arrive));

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

执行结果:

A0 arrive 2000
A1 arrive 3000
A3 arrive 4000
A2 arrive 7000
barrierAction :7057
A2 exit  wait0
A0 exit  wait5010
A1 exit  wait4006
A3 exit  wait3000

CyclicBarrier一个同步辅助类,允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)后才继续执行。

1.构造方法CyclicBarrier(int parties) ,parties参数互相等待的线程的数量
2.构造方法CyclicBarrier(int parties, Runnable barrierAction) ,barrierAction启动 barrier 时执行给定的屏障操作,该操作由最后一个进入 barrier 的线程执行
3.await(), 在所有线程在此 barrier 上调用 await 方法之前,将一直等待
4.await(long timeout, TimeUnit unit) ,与await()相比增加的超时时间
5.getNumberWaiting() ,在barrier等待的线程数量
6.getParties(),启动此 barrier 的线程数量
7.isBroken(),barrier是否处于损坏状态
8.reset(),重置barrier为其初始状态

你可能感兴趣的:(Java并发与多线程,java,并发,多线程,CyclicBarrier)