如何一文了解CountDownLatch(火箭发射倒计时-JUC)

本文深入探讨了CountDownLatch在多线程同步中的应用,通过两个具体案例:看门员等待所有人出门后锁门和秦始皇统一六国,详细解释了CountDownLatch如何确保主线程在所有前置线程完成任务后继续执行。

CountDownLatch内容解释

CountDownLatch只有带参数int n的构造器。表示从n开始至0倒计时,当Count为0时,则规定的操作才可以执行

使用场景

已知某个线程是用来做收尾工作的,只能等待其他前提线程都执行完时,这个收尾线程才能进行工作。
则在初始化countDownLatch对象时,传入其他线程数。在每个线程内部执行完后调用countDownLatch.countDown()方法实现一次计数。在收尾线程前一行执行countDownLatch.await()方法,表示当前线程等待计数归0再接着执行。

1.代码模拟5个线程需要出门,由最后一个线程进行锁门

锁门线程只能等待5个前提线程都出门后,才能开始执行

未使用CountDownLatch计数对象的代码Demo

public class CountDownLatchDemo {
    public static void main(String[] args) {
        for(int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 出门");
            }, String.valueOf(i)).start();
        }

        System.out.println("看门员开始锁门");
    }
}


从下面运行结果中可看出产生了严重的后果,此时看门员没有等待所有人都出门,就已经把门锁上了。

在这里插入图片描述

使用CountDownLatch对象来计数前提线程的已执行数量。

package lock;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for(int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 出门");
                countDownLatch.countDown();
            }, String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println("看门员开始锁门");
    }
}

从运行结果可知,前提线程无序外出(执行),看门员在最后才进行锁门(执行)

在这里插入图片描述

2.代码模拟秦始皇灭六国而一统天下(必须六国灭亡,天下才能一统)

使用枚举类设置key、value
// 创建枚举类,给线程编号取名字
enum CountryEnum {
    ONE(1, "齐"),TWO(2, "楚"),THREE(3, "燕"),FOUR(4, "韩"),FIVE(5, "赵"),SIX(6, "魏");
    private Integer retCode;
    private String retMessage;
    CountryEnum(Integer retCode, String retMessage) {
        this.retCode = retCode;
        this.retMessage = retMessage;
    }
    public Integer getRetCode() {

        return retCode;
    }
    public String getRetMessage() {
        return retMessage;
    }
    // 遍历枚举
    public static CountryEnum forEach_CountryEnum(int index) {
        CountryEnum[] values = CountryEnum.values();
        for (CountryEnum element : values) {
            if (index == element.getRetCode()) {
                return element;
            }
        }
        return null;
    }
}

主线程创建六个线程灭亡六国。由主线程统一全国

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for(int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 国被灭亡了");
                countDownLatch.countDown();
                // 创建枚举类CountryEnum,传入key值,获得value,给线程取名
            }, CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
        }
        countDownLatch.await();
        System.out.println("秦始皇统一了天下");
    }

运行结果中主线程等待六个前提线程执行完才开始执行

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值