JUC-how to use CountDownLatch

18 篇文章 0 订阅

in JUC kit package,CountDownLatch is a frequently-used class in specific concurrent sence,such as the last execution.

as we use countDownLatch's getCount() method to judge the last execution when to run.

the following code is to use CountDown Latch to solve the problem.

package JavaAdvanced;

import java.util.concurrent.CountDownLatch;

/**
 * @author 韦海涛
 * @version 1.0
 * @date 4/5/2021 12:39 AM
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(4);

        for (int i = 0; i < 4; i++) {
            final String temp = i+"";
            new Thread(()->{
                System.out.println("now is\t"+Thread.currentThread().getName()+"run");
                countDownLatch.countDown();
            },temp).start();
        }

        while (countDownLatch.getCount()!=0){
            countDownLatch.await();
        }
        System.out.println(Thread.currentThread().getName()+" have run to zero");


    }
}

if we need execute orderly.how to implement it?

package JavaAdvanced;

import java.util.concurrent.CountDownLatch;

/**
 * @author 韦海涛
 * @version 1.0
 * @date 4/5/2021 12:39 AM
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(4);

        for (int i = 1; i <= 4; i++) {
            final int temp = i;
            new Thread(()->{
                System.out.println("now is\t"+Thread.currentThread().getName()+"run");
                countDownLatch.countDown();
            },NumEnum.foreach_elemnt(temp).getMessage()).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+" have run to zero");


    }
}
package JavaAdvanced;

/**
 * @author 韦海涛
 * @version 1.0
 * @date 4/5/2021 1:11 AM
 */
public enum NumEnum {
    ONE(1,"第1位同学"),
    TWO(2,"第2位同学"),
    THREE(3,"第3位同学"),
    THIRD(4,"第4位同学");
    private int id;
    private String message;

    NumEnum(int id,String message){
        this.id = id;
        this.message = message;
    }

    public static NumEnum foreach_elemnt(int index){
        NumEnum[] myArray = NumEnum.values();
        for(NumEnum numEnum:myArray){
            if(numEnum.getId()==index){
                return numEnum;
            }
        }
        return null;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,您想了解关于Java并发编程中的CountDownLatch吗? CountDownLatchJava并发编程中非常重要的一个工具类,它可以让某个线程等待其他线程完成后再继续执行。它的作用类似于倒计时门闩,当count值减为0时,所有等待者都会被唤醒。 CountDownLatch是一次性的,也就是说,它的计数器只能使用一次。如果需要重复使用,可以考虑使用CyclicBarrier。 在使用CountDownLatch时,我们需要先创建一个CountDownLatch对象,并指定计数器的初始值。然后在需要等待的线程中调用await()方法进行等待,同时在其他线程中调用countDown()方法进行计数器的减1操作。 举个例子,假设我们有一个需求:主线程需要等待两个子线程完成后再执行。那么可以这样编写代码: ```java import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "执行开始"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "执行完毕"); countDownLatch.countDown(); }, "线程1").start(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "执行开始"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "执行完毕"); countDownLatch.countDown(); }, "线程2").start(); System.out.println(Thread.currentThread().getName() + "等待子线程执行完毕"); countDownLatch.await(); System.out.println(Thread.currentThread().getName() + "所有子线程执行完毕,继续执行主线程"); } } ``` 在上面的例子中,我们首先创建了一个计数器初始值为2的CountDownLatch对象,然后创建了两个线程分别进行一些操作,并在操作结束后调用countDown()方法进行计数器减1操作。在主线程中,我们调用await()方法进行等待,直到计数器减为0时,主线程才会继续执行。 希望能够对您有所帮助!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值