CyclicBarrier介绍

package com.karl.concurrent.utils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by karl.
 */
public class CyclicBarrierTest {
    public static class Task implements Runnable{
        private CyclicBarrier barrier;

        public Task(CyclicBarrier barrier){
            this.barrier = barrier;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" is waiting the barrier.");
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" cross the barrier");

        }

    }

    public static void main(String[] args) {
        //也可以只有第一个参数,表示参与者数目,即当3个参数与者到达barrier,则跨过barrier
        //第二个参数是一个线程,这个表示指定数目的线程到到达barrier后,将回执行这个线程。
        CyclicBarrier cb = new CyclicBarrier(3, new Runnable() {
            @Override
            public void run() {
                System.out.println("all parties are arrived at barrier,lets play");
            }
        }) ;
        Thread t1 = new Thread(new Task(cb), "Thread 1");
        Thread t2 = new Thread(new Task(cb), "Thread 2");
        Thread t3 = new Thread(new Task(cb), "Thread 3");
        Thread t4 = new Thread(new Task(cb), "Thread 4");
        Thread t5 = new Thread(new Task(cb), "Thread 5");
        Thread t6 = new Thread(new Task(cb), "Thread 6");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        cb.reset();  //重新设置barrier
    }
}

结果:

Thread 1 is waiting the barrier.
Thread 2 is waiting the barrier.
Thread 3 is waiting the barrier.
all parties are arrived at barrier,lets play
Thread 3 cross the barrier
Thread 1 cross the barrier
Thread 2 cross the barrier
Thread 4 is waiting the barrier.
Thread 5 is waiting the barrier.
Thread 6 is waiting the barrier.
all parties are arrived at barrier,lets play
Thread 6 cross the barrier
Thread 4 cross the barrier
Thread 5 cross the barrier

Process finished with exit code 0
原文地址:https://www.cnblogs.com/zhonghan/p/5009841.html