【多线程】CountDownLatch的简单实现

通过上一篇对CountDownLatch的使用,我们也明白了他的基本原理,接下来我们一起来实现一个CountDownLatch的基础效果

在这里插入图片描述

新建一个抽象类,包含countDownLatch需要的参数和方法

package com.atguigu.signcenter.nosafe.chouxiang;

/**
 * @author: jd
 * @create: 2024-09-03
 */
public abstract class Latch {

    // 控制了多少线程完成后门阀才能打开
    protected int limit;

    //构造函数
    public  Latch(int limit){
        this.limit =limit;
    }

    // 方法使得线程一直等待
    public abstract void await() throws InterruptedException;

    //当前任务线程完成工作之后调用该方法使得计数器减一
    public abstract void countDe();

    // 获取当前还有多少个线程没有完成任务
    public abstract int getUnArrived();


}

现这个抽象类,并写入具体逻辑代码

package com.atguigu.signcenter.nosafe.chouxiang.chouxiangImpl;

import com.atguigu.signcenter.nosafe.chouxiang.Latch;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: jd
 * @create: 2024-09-03
 */
public class LatchImpl extends Latch {
    //创建锁对象
    private final Lock lock = new ReentrantLock();
    //创建条件对象,但是作用待深入研究
    private final Condition condition = lock.newCondition();

    //LatchImpl的构造方法,用于计数器的初始化
    public  LatchImpl(int limit){
        super(limit);
    }

    /**
     * 重写等待方法
     * @throws InterruptedException
     */
    @Override
    public void await() throws InterruptedException {
        lock.lock();
        while (limit > 0){
            //如果进入到这里面之后,在await之后,会直接释放掉锁,不走后面的unlock()了;
            condition.await();
        }
        lock.unlock();

    }

    /**
     * 重写计数器减一方法
     */
    @Override
    public void countDe() {
        lock.lock();
        while (limit<0){
            throw new IllegalStateException();
        }
        limit--;
        //对 condition.await(); 的线程进行唤醒,让他继续执行。
        condition.signalAll();
        lock.unlock();
    }

    /**
     * 重写获取 当前未完成线程方法
     * @return
     */
    @Override
    public int getUnArrived() {
        return limit;
    }
}

测试

package com.atguigu.signcenter.nosafe;

import com.atguigu.signcenter.nosafe.chouxiang.chouxiangImpl.LatchImpl;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: jd
 * @create: 2024-09-03
 */
public class LatchTest {

    // 创建一个线程池来执行任务
    static final ThreadPoolExecutor executor = new ThreadPoolExecutor(6,10,30L,
            TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory());

    public static void main(String[] args) throws InterruptedException {
        LatchImpl latch = new LatchImpl(2);

        //模拟小红
        executor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("小红出发了");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDe();
                System.out.println("小红到了");
            }
        });

        //模拟小明
        executor.submit(() -> {
            System.out.println("小明出发了");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDe();
            System.out.println("小明到了");
        });
        latch.await();
        System.out.println("都到了,一起去爬山了");
        executor.shutdown();

    }
}

测试结果:
在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执键行天涯

码你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值