0
点赞
收藏
分享

微信扫一扫

基于CountDownLatch实现多个子任务执行结果汇总

分湖芝蘭 2022-04-15 阅读 78

文章目录

1、未使用 CountDownLatch

public class TestCountDownLatch {

    public static void main(String[] args) throws InterruptedException {
        TestCountDown testCountDown = new TestCountDown();
        Thread threadA = new Thread(testCountDown);
        Thread threadB = new Thread(testCountDown);
        Thread threadC = new Thread(testCountDown);
        Thread threadD = new Thread(testCountDown);
        Thread threadE = new Thread(testCountDown);
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
        threadE.start();
        System.out.println("全部执行完");
    }

    public static class TestCountDown implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {}
            System.out.println("线程:" + Thread.currentThread().getName() + "执行完!");
        }
    }
}

结果

子线程还没执行完,主线程就先执行完了
在这里插入图片描述

2、使用 CountDownLatch

public class TestCountDownLatch {

    public static CountDownLatch countDownLatch = new CountDownLatch(5);

    public static void main(String[] args) throws InterruptedException {
        TestCountDown testCountDown = new TestCountDown();

        Thread threadA = new Thread(testCountDown);
        Thread threadB = new Thread(testCountDown);
        Thread threadC = new Thread(testCountDown);
        Thread threadD = new Thread(testCountDown);
        Thread threadE = new Thread(testCountDown);
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
        threadE.start();
        countDownLatch.await();
        System.out.println("全部执行完");
    }

    public static class TestCountDown implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {}
            System.out.println("线程:" + Thread.currentThread().getName() + "执行完!");
            countDownLatch.countDown();
        }
    }
}

结果

等待子线程全部执行完,主线程才执行完毕
在这里插入图片描述

举报

相关推荐

0 条评论