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标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

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

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

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

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

python中列表应用和扩展性实用详解

《python中列表应用和扩展性实用详解》文章介绍了Python列表的核心特性:有序数据集合,用[]定义,元素类型可不同,支持迭代、循环、切片,可执行增删改查、排序、推导式及嵌套操作,是常用的数据处理... 目录1、列表定义2、格式3、列表是可迭代对象4、列表的常见操作总结1、列表定义是处理一组有序项目的

C#中的Converter的具体应用

《C#中的Converter的具体应用》C#中的Converter提供了一种灵活的类型转换机制,本文详细介绍了Converter的基本概念、使用场景,具有一定的参考价值,感兴趣的可以了解一下... 目录Converter的基本概念1. Converter委托2. 使用场景布尔型转换示例示例1:简单的字符串到

Spring Boot Actuator应用监控与管理的详细步骤

《SpringBootActuator应用监控与管理的详细步骤》SpringBootActuator是SpringBoot的监控工具,提供健康检查、性能指标、日志管理等核心功能,支持自定义和扩展端... 目录一、 Spring Boot Actuator 概述二、 集成 Spring Boot Actuat

PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例

《PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例》词嵌入解决NLP维度灾难,捕捉语义关系,PyTorch的nn.Embedding模块提供灵活实现,支持参数配置、预训练及变长... 目录一、词嵌入(Word Embedding)简介为什么需要词嵌入?二、PyTorch中的nn.Em

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima

Redis中Stream详解及应用小结

《Redis中Stream详解及应用小结》RedisStreams是Redis5.0引入的新功能,提供了一种类似于传统消息队列的机制,但具有更高的灵活性和可扩展性,本文给大家介绍Redis中Strea... 目录1. Redis Stream 概述2. Redis Stream 的基本操作2.1. XADD