CompletableFuture-应用

2024-08-21 00:20
文章标签 应用 completablefuture

本文主要是介绍CompletableFuture-应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述
可以看到CompletableFuture实现了CompletionStage 和Future的两个接口。CompletionStage提供了任务之间的衔接能力,而Future则是经常用于阻塞获取结果。

CompletableFuture 的内部使用了基于 ForkJoinPool 的线程池,这种线程池可以高效地调度和执行任务。CompletableFuture 的非阻塞特性得益于其对任务完成的监听机制。当任务完成时,它会遍历所有注册的回调函数,并在合适的线程中执行这些回调。通过这种机制,CompletableFuture 能够在任务完成后及时返回结果或触发后续处理逻辑,而不会阻塞主线程的执行。

使用场景

场景一 并行执行多个任务
public class FutureDemo {public static void main(String[] args) {long start = System.currentTimeMillis();CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {task1();});CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {task2();});CompletableFuture<Void> f3 = CompletableFuture.runAsync(() -> {task3();});CompletableFuture<Void> allOf = CompletableFuture.allOf(f1, f2, f3);try {// 所有任务一起并行allOf.get();System.out.println("all task finish cost:" + (System.currentTimeMillis() - start));} catch (InterruptedException e) {} catch (ExecutionException e) {throw new RuntimeException(e);}System.out.println("main thread finsh!!!");}public static void task1() {try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task1 finish cost 3000!!!");}public static void task2() {try {Thread.sleep(6000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task2 finish cost 6000!!!");}public static void task3() {try {Thread.sleep(9000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task3 finish cost 9000!!!");}
}

可以看到运行结果,多个任务并行执行,总任务完成时间是耗时最长的任务:
在这里插入图片描述

场景一 父任务执行完毕以后 开启多个子任务
public class FutureDemo {public static void main(String[] args) {long start = System.currentTimeMillis();try {CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {task1();});// 任务一执行完毕f1.get();CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {task2();});CompletableFuture<Void> f3 = CompletableFuture.runAsync(() -> {task3();});CompletableFuture<Void> allOf = CompletableFuture.allOf(f2, f3);// 任务2,3并行allOf.get();System.out.println("all task finish cost:" + (System.currentTimeMillis() - start));} catch (InterruptedException e) {} catch (ExecutionException e) {throw new RuntimeException(e);}System.out.println("main thread finsh!!!");}public static void task1() {try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task1 finish cost 3000!!!");}public static void task2() {try {Thread.sleep(6000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task2 finish cost 6000!!!");}public static void task3() {try {Thread.sleep(9000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task3 finish cost 9000!!!");}
}

在这里插入图片描述
由于第一个任务阻塞执行完毕,2,3任务并行执行,时间最长的执行了9秒所以总时间是12左右。

场景三 场景一的变种

A B
C
我们希望A和C都执行完以后继续往后执行,并且C的执行顺序严格在B以后。

public class FutureDemo {public static void main(String[] args) {long start = System.currentTimeMillis();try {CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {task1();});CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {task2();});CompletableFuture<Void> f3 = f2.thenRunAsync(() -> {task3();});CompletableFuture<Void> allOf = CompletableFuture.allOf(f1, f3);allOf.get();System.out.println("all task finish cost:" + (System.currentTimeMillis() - start));} catch (InterruptedException e) {} catch (ExecutionException e) {throw new RuntimeException(e);}System.out.println("main thread finsh!!!");}public static void task1() {try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task1 finish cost 3000!!!");}public static void task2() {try {Thread.sleep(6000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task2 finish cost 6000!!!");}public static void task3() {try {Thread.sleep(9000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task3 finish cost 9000!!!");}
}

在这里插入图片描述
由于任务一是一个任务,而任务2和3是一起执行,所以相当于是两个任务并行,时间最长是任务2,3加在一起。

场景四 任取其一

这种场景什么时候使用呢?比如我们对数处理做了不同的策略,我们不知道哪个计算的速度更快,我们希望谁先出结果就优先使用。

public class FutureDemo {public static void main(String[] args) {long start = System.currentTimeMillis();try {CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {task1();});CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {task2();});CompletableFuture<Void> f3 = CompletableFuture.runAsync(() -> {task3();});CompletableFuture<Object> anyOf = CompletableFuture.anyOf(f1, f2, f3);// 任务2,3并行anyOf.get();System.out.println("all task finish cost:" + (System.currentTimeMillis() - start));} catch (InterruptedException e) {} catch (ExecutionException e) {throw new RuntimeException(e);}System.out.println("main thread finsh!!!");}public static void task1() {try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task1 finish cost 3000!!!");}public static void task2() {try {Thread.sleep(6000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task2 finish cost 6000!!!");}public static void task3() {try {Thread.sleep(9000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("task3 finish cost 9000!!!");}
}

在这里插入图片描述
可以看到这里肯定是耗时最短的任务1先执行完毕,所以 总耗时为3秒。
参考资料:
https://www.yuque.com/itlaoqi/uprrn9/nakraehf13w4xdy4

这篇关于CompletableFuture-应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

如何确定哪些软件是Mac系统自带的? Mac系统内置应用查看技巧

《如何确定哪些软件是Mac系统自带的?Mac系统内置应用查看技巧》如何确定哪些软件是Mac系统自带的?mac系统中有很多自带的应用,想要看看哪些是系统自带,该怎么查看呢?下面我们就来看看Mac系统内... 在MAC电脑上,可以使用以下方法来确定哪些软件是系统自带的:1.应用程序文件夹打开应用程序文件夹

Python Flask 库及应用场景

《PythonFlask库及应用场景》Flask是Python生态中​轻量级且高度灵活的Web开发框架,基于WerkzeugWSGI工具库和Jinja2模板引擎构建,下面给大家介绍PythonFl... 目录一、Flask 库简介二、核心组件与架构三、常用函数与核心操作 ​1. 基础应用搭建​2. 路由与参

Spring Boot中的YML配置列表及应用小结

《SpringBoot中的YML配置列表及应用小结》在SpringBoot中使用YAML进行列表的配置不仅简洁明了,还能提高代码的可读性和可维护性,:本文主要介绍SpringBoot中的YML配... 目录YAML列表的基础语法在Spring Boot中的应用从YAML读取列表列表中的复杂对象其他注意事项总

电脑系统Hosts文件原理和应用分享

《电脑系统Hosts文件原理和应用分享》Hosts是一个没有扩展名的系统文件,当用户在浏览器中输入一个需要登录的网址时,系统会首先自动从Hosts文件中寻找对应的IP地址,一旦找到,系统会立即打开对应... Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址域名与其对应

CSS 样式表的四种应用方式及css注释的应用小结

《CSS样式表的四种应用方式及css注释的应用小结》:本文主要介绍了CSS样式表的四种应用方式及css注释的应用小结,本文通过实例代码给大家介绍的非常详细,详细内容请阅读本文,希望能对你有所帮助... 一、外部 css(推荐方式)定义:将 CSS 代码保存为独立的 .css 文件,通过 <link> 标签