CountDownLatch(火箭发射倒计时)

CountDownLatch类是JUC包里面的一个倒计时控制类,类似是火箭发射倒计时,具体实现如下:

package com.atnuocai.model;

import java.util.concurrent.CountDownLatch;

/**
 * Created by on 27/11/2021
 *java.util.CountDownLatch(火箭发射倒计时)
 * 让一线程阻塞直到另一些线程完成一系列操作才被唤醒。
 *
 * CountDownLatch主要有两个方法(await(),countDown())。
 *
 * 当一个或多个线程调用await()时,调用线程会被阻塞。其它线程调用countDown()会将计数器减1(调用countDown方法的线程不会阻塞),当计数器的值变为零时,因调用await方法被阻塞的线程会被唤醒,继续执行
 * @author 刘杰杰
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws Exception{
      //  unUseCountDown();
      // useCountDown();
        //秦灭六国,统一华夏
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"被灭");
                countDownLatch.countDown();
            },CountryEnum.getCountry(i).getReCountry()).start();
        }
            countDownLatch.await();
            System.out.println("==============");
            System.out.println("秦灭六国,统一华夏");
    }

    /**
     * 使用CountDownLatch之后
     * @throws InterruptedException
     */
    private static void useCountDown() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                System.out.println("学生"+Thread.currentThread().getName()+"离开教室");
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println("===================");
        System.out.println("班长最后离开教室");
    }

    /**
     * 未使用CountDownLatch方法之前
     */
    private static void unUseCountDown() {
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                System.out.println("学生"+ Thread.currentThread().getName() +"离开教室!");
            },String.valueOf(i)).start();
        }
        System.out.println("=============");
        System.out.println("班长最后离开教室");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值