Java:CountDownLatch等待所有线程执行结束后继续执行

CountDownLatch可以使一个或多个线程等待其他线程各自执行完毕后再执行

class WorkThread implements Runnable {
    private CountDownLatch countDownLatch;

    public WorkThread(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + " 干活结束");
        this.countDownLatch.countDown();

    }
}

package com.demo.atomic;

import java.util.concurrent.CountDownLatch;

public class countDownLatchDemo {
    public static void main(String[] args) {
        // 初始化等待线程个数: 2个
        CountDownLatch countDownLatch = new CountDownLatch(2);

        WorkThread workThread1 = new WorkThread(countDownLatch);
        WorkThread workThread2 = new WorkThread(countDownLatch);

        new Thread(workThread1).start();
        new Thread(workThread2).start();

        // 阻塞主线程,等待子线程全部结束继续
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("结束了");
    }
}

如果不等待,执行结果

结束了
Thread-0 干活结束
Thread-1 干活结束

如果等待, 执行结果

Thread-1 干活结束
Thread-0 干活结束
结束了
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页