JUC之CountdownLatch使用详解

 更新时间:2023年12月16日 08:50:59   作者:小晨想好好学习  
这篇文章主要介绍了JUC之CountdownLatch使用详解,CountdownLatch 用来进行线程同步协作,等待所有线程完成倒计时,
其中构造参数用来初始化等待计数值,await() 用来等待计数归零,countDown() 用来让计数减一,需要的朋友可以参考下

一、是什么?

CountdownLatch 用来进行线程同步协作,等待所有线程完成倒计时。

其中构造参数用来初始化等待计数值,await() 用来等待计数归零,countDown() 用来让计数减一

二、demo演示

public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test5();
    }
    private static void test5() {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService service = Executors.newFixedThreadPool(4);
        service.submit(() -> {
            log.debug("begin...");
            sleep(1);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        });
        service.submit(() -> {
            log.debug("begin...");
            sleep(1.5);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        });
        service.submit(() -> {
            log.debug("begin...");
            sleep(2);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        });
        service.submit(()->{
            try {
                log.debug("waiting...");
                latch.await();
                log.debug("wait end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

在这里插入图片描述

三、应用之同步等待多线程准备完毕

 private static void test2() throws InterruptedException {
        AtomicInteger num = new AtomicInteger(0);
        ExecutorService service = Executors.newFixedThreadPool(10, (r) -> {
            return new Thread(r, "t" + num.getAndIncrement());
        });
        CountDownLatch latch = new CountDownLatch(10);
        String[] all = new String[10];
        Random r = new Random();
        for (int j = 0; j < 10; j++) {
            int x = j;
            service.submit(() -> {
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(r.nextInt(100));
                    } catch (InterruptedException e) {
                    }
                    all[x] = Thread.currentThread().getName() + "(" + (i + "%") + ")";
                    System.out.print("\r" + Arrays.toString(all));
                }
                latch.countDown();
            });
        }
        latch.await();
        System.out.println("\n游戏开始...");
        service.shutdown();
    }

四、 应用之同步等待多个远程调用结束

    private static void test3() throws InterruptedException, ExecutionException {
        RestTemplate restTemplate = new RestTemplate();
        log.debug("begin");
        ExecutorService service = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(4);
        service.submit(() -> {
            Map<String, Object> response = restTemplate.getForObject("http://localhost:8080/order/{1}", Map.class, 1);
            log.debug("{}",response);
            latch.countDown();
        });
       service.submit(() -> {
            Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 1);
           log.debug("{}",response1);
           latch.countDown();
        });
        service.submit(() -> {
            Map<String, Object> response2 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 2);
            log.debug("{}",response2);
            latch.countDown();
        });
        service.submit(() -> {
            Map<String, Object> response3 = restTemplate.getForObject("http://localhost:8080/logistics/{1}", Map.class, 1);
            log.debug("{}",response3);
            latch.countDown();
        });
        latch.await();
        log.debug("执行完毕");
        service.shutdown();
    }

到此这篇关于JUC之CountdownLatch使用详解的文章就介绍到这了,更多相关CountdownLatch使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中的Cookie和Session详细解析

    Java中的Cookie和Session详细解析

    这篇文章主要介绍了Java中的Cookie和Session详细解析,客户端会话技术,服务端给客户端的数据,存储于客户端(浏览器),由于是保存在客户端上的,所以存在安全问题,需要的朋友可以参考下
    2024-01-01
  • PageHelper引发的幽灵数据问题解析

    PageHelper引发的幽灵数据问题解析

    这篇文章主要为大家介绍了PageHelper引发的幽灵数据问题解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • Java线性结构中的双向链表实现原理

    Java线性结构中的双向链表实现原理

    这篇文章将给大家详细讲解双向链表的内容,尤其是会通过代码来进行链表的操作,文中的代码示例介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2023-07-07
  • Java SE使用数组实现高速数字转换功能

    Java SE使用数组实现高速数字转换功能

    随着大数据时代的到来,数字转换功能变得越来越重要,在Java开发中,数字转换功能也是经常用到的,下面我们就来学习一下如何使用Java SE数组实现高速的数字转换功能吧
    2023-11-11
  • 在Windows上实现多JDK快速切换的高效方法

    在Windows上实现多JDK快速切换的高效方法

    在现代软件开发过程中,Java作为一种广泛应用的编程语言,其不同版本之间的兼容性和功能差异使得开发者经常需要在多个JDK版本之间进行切换,这篇文章主要介绍了在Windows上实现多JDK快速切换的高效方法,需要的朋友可以参考下
    2026-01-01
  • 一小时迅速入门Mybatis之bind与多数据源支持 Java API

    一小时迅速入门Mybatis之bind与多数据源支持 Java API

    这篇文章主要介绍了一小时迅速入门Mybatis之bind与多数据源支持 Java API,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09
  • 在SpringBoot项目中使用Spring Cloud Sentinel实现流量控制

    在SpringBoot项目中使用Spring Cloud Sentinel实现流量控制

    随着微服务架构的流行,服务之间的调用变得越来越频繁和复杂,流量控制是保障系统稳定性的重要手段之一,它可以帮助我们避免因过载而导致的服务不可用,本文将介绍如何在Spring Boot项目中使用Spring Cloud Sentinel来实现流量控制,需要的朋友可以参考下
    2024-08-08
  • Spring Cloud如何切换Ribbon负载均衡模式

    Spring Cloud如何切换Ribbon负载均衡模式

    这篇文章主要介绍了Spring Cloud如何切换Ribbon负载均衡模式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • MyBatisPlus自定义SQL的实现

    MyBatisPlus自定义SQL的实现

    MyBatisPlus提供了自定义SQL功能,允许开发者在Mapper接口中定义方法,并通过XML文件或注解编写SQL语句,本文详解了如何在MP中使用自定义SQL,感兴趣的可以了解一下
    2024-09-09
  • Java实现图片验证码具体代码

    Java实现图片验证码具体代码

    这篇文章主要为大家详细介绍了Java实现图片验证码具体代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10

最新评论