133.并发工具类-CountDownLatch__

该博客展示了如何使用Java并发工具类CountDownLatch来实现线程间的同步。通过创建一个倒计时器,妈妈线程等待三个孩子线程(小明、小红和小刚)各自吃完饺子后才开始收拾碗筷。每个孩子线程会依次打印吃饺子的过程,并在完成后调用countDown()方法减少计数器。这个例子清晰地解释了CountDownLatch在多线程编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.itheima.mycountDown;

import java.util.concurrent.CountDownLatch;

public class MotherThead extends Thread{
    private CountDownLatch countDownLatch;
    public MotherThead(CountDownLatch countDownLatch) {
        this.countDownLatch=countDownLatch;
    }

    @Override
    public void run() {
        try {
            //
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("妈妈在收拾碗筷");
    }
}
package com.itheima.mycountDown;

import java.util.concurrent.CountDownLatch;

public class ChileThread1 extends Thread{
    private CountDownLatch countDownLatch;
    public ChileThread1(CountDownLatch countDownLatch) {
        this.countDownLatch=countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 0; i <= 10; i++) {
            System.out.println(getName()+"在吃第"+i+"个饺子");
        }
        countDownLatch.countDown();
    }
}
package com.itheima.mycountDown;

import java.util.concurrent.CountDownLatch;

public class ChileThread2 extends Thread{
    private CountDownLatch countDownLatch;
    public ChileThread2(CountDownLatch countDownLatch) {
        this.countDownLatch=countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 0; i <= 15; i++) {
            System.out.println(getName()+"在吃第"+i+"个饺子");
        }
        countDownLatch.countDown();
    }
}
package com.itheima.mycountDown;

import java.util.concurrent.CountDownLatch;

public class ChileThread3 extends Thread{
    private CountDownLatch countDownLatch;
    public ChileThread3(CountDownLatch countDownLatch) {
        this.countDownLatch=countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 0; i <= 20; i++) {
            System.out.println(getName()+"在吃第"+i+"个饺子");
        }
        countDownLatch.countDown();
    }
}
package com.itheima.mycountDown;

import java.util.concurrent.CountDownLatch;

public class MyCountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch countDownLatch=new CountDownLatch(3);
        MotherThead motherThead=new MotherThead(countDownLatch);
        motherThead.start();
        ChileThread1 t1=new ChileThread1(countDownLatch);
        t1.setName("小明");

        ChileThread2 t2=new ChileThread2(countDownLatch);
        t2.setName("小红");

        ChileThread3 t3=new ChileThread3(countDownLatch);
        t3.setName("小刚");
        t1.start();
        t2.start();
        t3.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值