多线程-CountDownLatch与CyclicBarrier

等待线程将结果执行完才能向下继续运行,类似于一个程序计数器,只有当计数器为0时代码才能向下运行

使用效果和join 一样但是比join更加灵活,例如可以用于线程池。

只适用于结果没有返回值的,如果结果有返回值还是用Future去获取。

future.get 是阻塞的 ,如果要设置任务超时时间则需要用future.isDone是否完成 再进行获取或者抛异常

样例代码
public class Main {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        executorService.submit(()->{
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        });
        executorService.submit(()->{
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        });
        executorService.submit(()->{
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        });
        countDownLatch.await();
    }
}

CyclicBarrier 程序计数可以重用

样例代码
public class Main {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
            // 任务结束后的逻辑

        });
        for (int i = 0; i < 3; i++) {
            executorService.submit(()->{
                try {
                    Thread.sleep(1);
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

            });
            executorService.submit(()->{
                try {
                    Thread.sleep(3);
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

            });
            executorService.submit(()->{
                try {
                    Thread.sleep(2);
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

            });
        }


    }
}
posted @ 2022-03-21 17:30  原来是晴天啊  阅读(19)  评论(0编辑  收藏  举报