首页 > 其他分享 >CountDownLatch

CountDownLatch

时间:2023-03-14 21:01:02浏览次数:39  
标签:cdl CountDownLatch 线程 countDownLatch new public

使用场景:让某一条线程等待其它线程执行完毕后再执行。

CountDownLatch cdl = new CountDownLatch(3):参数是等待线程的数量,并定义了一个计时器;

await():让线程等待,当计时器为0时,唤醒线程;

countDown():线程执行完毕时调用,计时器会减1;

案例:妈妈有三个孩子,三个孩子吃饺子,等三个孩子都吃完饺子妈妈才能收拾桌子

public class CountDownLatchDemo {

    public static void main(String[] args) {
        // 创建CountDownLatch对象,需要传递给4个线程,ChildThread1、2、3代码相同
        CountDownLatch cdl = new CountDownLatch(3);
        // 创建4个线程对象开启它们
        MotherThread mt = new MotherThread(cdl);
        mt.start();
        ChildThread1 t1 = new ChildThread1(cdl);
        ChildThread2 t2 = new ChildThread2(cdl);
        ChildThread3 t3 = new ChildThread3(cdl);

        t1.setName("小红");
        t2.setName("小明");
        t3.setName("小刚");

        t1.start();
        t2.start();
        t3.start();
    }
}
public class MotherThread extends Thread {

    private CountDownLatch countDownLatch;

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

    @Override
    public void run() {
        try {
            // 1、等孩子吃完,当计时器为0时,会自动唤醒这里等待的线程
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 2、三个孩子都吃完了开始收拾
        System.out.println("开始收拾了!");
    }

}
public class ChildThread1 extends Thread {

    private CountDownLatch countDownLatch;

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

    @Override
    public void run() {
        // 1、吃饺子
        for (int i = 1; i < 11; i++) {
            System.out.println(getName() + "开始吃第" + i + "个饺子");
        }

        // 2、吃完给妈妈说一声,计时器会减1
        countDownLatch.countDown();
    }

}

 

标签:cdl,CountDownLatch,线程,countDownLatch,new,public
From: https://www.cnblogs.com/weiduaini/p/17216309.html

相关文章