CountDownLatch 和 CyclicBarrier

40 阅读1分钟

CountDownLatch 使用,一次性的

     public static void main(String[] args)  {
        ExecutorService service = Executors.newCachedThreadPool();
        final CountDownLatch cdOrder = new CountDownLatch(1);
        final CountDownLatch cdAnswer = new CountDownLatch(4);
        for (int i = 0; i < 4; i++) {
            Runnable runnable = () -> {
                try {
                    System.out.println("选手" + Thread.currentThread().getName() + "正在等待裁判发布口令");
                    cdOrder.await();
                    System.out.println("选手" + Thread.currentThread().getName() + "已接受裁判口令");
                    Thread.sleep((long) (Math.random() * 10000));
                    System.out.println("选手" + Thread.currentThread().getName() + "到达终点");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    // 到终点了,在finally 执行,防止出现异常,主线程一直等待
                    cdAnswer.countDown();
                }
            };
            service.execute(runnable);
        }
        try {
            Thread.sleep((long) (Math.random() * 10000));
            System.out.println("裁判"+Thread.currentThread().getName()+"即将发布口令");
            System.out.println("裁判"+Thread.currentThread().getName()+"已发送口令,正在等待所有选手到达终点");
            cdAnswer.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // -1 表示发送口令
            cdOrder.countDown();
        }
        System.out.println("所有选手都到达终点");
        System.out.println("裁判"+Thread.currentThread().getName()+"汇总成绩排名");
        service.shutdown();
    }

Cyclicbarrier 使用,循环使用的

    public static void main(String[] args)  {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10, new Runnable() {
            @Override
            public void run() {
                System.out.println("先执行这句话,线程的后续代码才会继续执行,满10个,执行一次");
            }

            });
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(() -> {
                if (finalI % 2 == 0) {
                    try {
                        // 10个线程调用 await,所有的线程才会继续执行代码
                        cyclicBarrier.await();
                        System.out.println(Thread.currentThread().getName());
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }