[Java] CountDownLatch和ExecutorService的简单使用

2024-06-07 22:18

本文主要是介绍[Java] CountDownLatch和ExecutorService的简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • [Java] CountDownLatch和ExecutorService的简单使用
    • 一、前言
    • 二、记录

[Java] CountDownLatch和ExecutorService的简单使用

一、前言

  • 环境说明:

JDK:1.8

官方API文档:https://docs.oracle.com/javase/8/docs/api/index.html

参考:

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

二、记录

场景说明:

1.模拟多个动物,同时喂食,并记录过程

  • 动物接口
package com.demo.thread;/*** 动物接口* */
public interface IAnimal {/*** 喂食* */public String feeding() throws InterruptedException;}
  • 动物类:狗
package com.demo.thread;/*** 狗* */
public class Dog implements IAnimal {@Overridepublic String feeding() throws InterruptedException {Thread.sleep(3000); // 模拟耗时StringBuffer stringBuffer = new StringBuffer();stringBuffer.append("准备美味的骨头");stringBuffer.append(" > 开始喂食");return stringBuffer.toString();}
}
  • 动物类:猫
package com.demo.thread;/*** 猫* */
public class Cat implements IAnimal {@Overridepublic String feeding() throws InterruptedException {Thread.sleep(5000); // 模拟耗时StringBuffer stringBuffer = new StringBuffer();stringBuffer.append("准备美味的小鱼");stringBuffer.append(" > 开始喂食");return stringBuffer.toString();}
}
  • 任务类:喂食
package com.demo.thread;import java.util.Map;
import java.util.concurrent.CountDownLatch;/*** 任务类* */
public class FeedingTask implements Runnable {private String id;private IAnimal iAnimal;private CountDownLatch countDownLatch;private Map<String, String> map; // 结果// constructorpublic FeedingTask(String id, IAnimal iAnimal, CountDownLatch countDownLatch, Map<String, String> map){this.id = id;this.iAnimal = iAnimal;this.countDownLatch = countDownLatch;this.map = map;}@Overridepublic void run() {try {long start = System.currentTimeMillis(); // 开始时间戳String flow = iAnimal.feeding(); // 开始喂食map.put(id, flow); // 记录过程long end = System.currentTimeMillis(); // 结束时间戳System.out.println(id + " exec="+ (end - start) +"ms");} catch (InterruptedException e) {e.printStackTrace();}finally {countDownLatch.countDown(); // 计数器递减}}
}
  • 主入口
package com.demo.thread;import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class MainDemo {public static void main(String[] args) throws InterruptedException {Map<String, String> map = new HashMap<>();CountDownLatch countDownLatch = new CountDownLatch(2); // M 个喂食任务ExecutorService executorService = Executors.newFixedThreadPool(2); // N 个任务同时执行(线程池)// Dog FeedingexecutorService.execute(new FeedingTask("DOG", new Dog(), countDownLatch, map));// Cat FeedingexecutorService.execute(new FeedingTask("CAT", new Cat(), countDownLatch, map));// 等待所有动物喂食完成(等待计数器归零)countDownLatch.await();executorService.shutdown(); // 关闭执行线程池// 输出结果System.out.println(map.toString());}
}
  • 输出结果
DOG exec=3000ms
CAT exec=5000ms
{CAT=准备美味的小鱼 > 开始喂食, DOG=准备美味的骨头 > 开始喂食}

这篇关于[Java] CountDownLatch和ExecutorService的简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1040451

相关文章

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件