CyclicBarrier 使用

package com.thread.concurrent;

import java.util.concurrent.*;

public class CyclicBarrierDemo {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(9, new Runnable() {
        @Override
        public void run() {
            System.out.println("开始执行最后的任务H");
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
                System.out.println("任务H 执行完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Thread01(cyclicBarrier));
        }
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Thread02(cyclicBarrier));
        }
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Thread03(cyclicBarrier));
        }
        executorService.shutdown();

    }

    static class Thread01 implements Runnable {

        private CyclicBarrier cyclicBarrier;

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

        @Override
        public void run() {
            try {
                System.out.println("开始执行任务A");
                TimeUnit.MILLISECONDS.sleep(1000);
                cyclicBarrier.await();
                System.out.println("冲破屏障");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    static class Thread02 implements Runnable {

        private CyclicBarrier cyclicBarrier;

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

        @Override
        public void run() {
            try {
                System.out.println("开始执行任务B");
                TimeUnit.MILLISECONDS.sleep(2000);
                cyclicBarrier.await();
                cyclicBarrier.reset();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    static class Thread03 implements Runnable {

        private CyclicBarrier cyclicBarrier;

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

        @Override
        public void run() {
            try {
                System.out.println("开始执行任务C");
                TimeUnit.MILLISECONDS.sleep(3000);
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(java多线程)