java并发编程-CyclicBarrier

CyclicBarrier:允许一组线程全部等待彼此达到共同屏障点的同步辅助类
作用:任何一个线程完成任务之前,所有线程都必须等待
测试代码:
public class TestThread extends Thread {
    private CyclicBarrier cyclicBarrier;

    public TestThread(CyclicBarrier cyclicBarrier){
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"-到达");
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
public class MyTest {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("已经全部到达");
            }
        });
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for(int i=0;i<5;i++){
            TestThread thread = new TestThread(cyclicBarrier);
            executorService.execute(thread);
        }
        executorService.shutdown();
    }
}
测试结果:
pool-1-thread-1-到达
pool-1-thread-2-到达
pool-1-thread-5-到达
pool-1-thread-3-到达
pool-1-thread-4-到达
已经全部到达

上一篇:Java中CountDownLatch和CyclicBarrier


下一篇:CyclicBarrier示例程序