java 8 新特性CompletableFuture使用

2024-06-08 10:04

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

准备工作:定义一个线程池

        ExecutorService pool= Executors.newFixedThreadPool(3,(Runnable r)->{Thread t=new Thread(r);t.setDaemon(true);return t;});

一、执行方式
1、对于有返回值的

CompletableFuture<String> future=CompletableFuture.supplyAsync(()->{return "主任务返回结果";},pool).handle((result,throwable)->{if(throwable!=null){return "处理异常结果";}System.out.println("结果回调");System.out.println(result);return "统一返回结果:"+result;});String result=future.get();System.out.println(result);

2、对应没有返回值的

ExecutorService pool= Executors.newFixedThreadPool(3,(Runnable r)->{Thread t=new Thread(r);t.setDaemon(true);return t;});CompletableFuture<Void> future=CompletableFuture.runAsync(()->{System.out.println("业务1");System.out.println("业务2");},pool);future.join();

二、设置回调

CompletableFuture<String> future=CompletableFuture.supplyAsync(()->{System.out.println("业务1");return "11111";},pool).whenComplete((v,throwable)->{System.out.println("回调结果");System.out.println(v);});future.join();

三、异步任务的串行:
即流水线方式,一个任务结束另一个任务开始执行
1、thenApplyAsync方式:第一个任务结束,第二个任务用第一个任务的结果作为参数,并开启第二个任务的执行,第二个任务返回新的结果。

CompletableFuture<String> funtue=CompletableFuture.supplyAsync(()->"a",pool).thenApplyAsync(v->{System.out.println("主任务结果"+v);return "b";},pool).thenApplyAsync(v->{System.out.println("次任务结果"+v);return "c";},pool);System.out.println(funtue.get());

2、thenRunAsync:第一个任务结束,第二个任务开始,并且第二个任务无需参数(与上一个任务执行结果无关),并且第二个任务无返回值

CompletableFuture<Void> funtue=CompletableFuture.supplyAsync(()->"a",pool).thenRunAsync(()->{System.out.println("谢谢小星星");System.out.println("异步执行");},pool);funtue.join();

3、thenAcceptAsync:第一个任务结束,第二个任务用第一个任务的结果作为参数,并开启第二个任务的执行,第二个任务无返回值。

CompletableFuture<Void> funtue=CompletableFuture.supplyAsync(()->"a",pool).thenAcceptAsync(v->{System.out.println("上一步结果");System.out.println(v);},pool);funtue.join();

4、thenComposeAsync:与thenApplyAsync类似,不同的是第二个任务的返回结果是CompletableFuture类型的

        CompletableFuture<String> funtue=CompletableFuture.supplyAsync(()->"a",pool).thenComposeAsync(v->{System.out.println("上一步计算结果:"+v);return CompletableFuture.supplyAsync(()->"b",pool);},pool);System.out.println(funtue.get());

四、异步任务的合并执行:

例如一共有三个任务,第三个任务需要再第一个任务和第二个任务都执行完成后才能执行第三个任务
1、thenCombineAsync:调用方为第一个任务的CompletionStage,第一个参数为第二个任务的CompletionStage。在第一个和第二个任务都执行完成后,开始执行第三个任务,第三个任务的参数分别为第一个、第二个任务的返回结果,并且第三个任务需要返回新的结果

CompletableFuture<Integer> future1=CompletableFuture.supplyAsync(()->3,pool);CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->6,pool);CompletableFuture<Integer> future3=future1.thenCombineAsync(future2,(m,v)->m*v,pool);System.out.println(future3.get());

2、runAfterBothAsync::调用方为第一个任务的CompletionStage,第一个参数为第二个任务的CompletionStage。在第一个和第二个任务都执行完成后,开始执行第三个任务,第三个任务与第一个、第二个任务的返回结果无关,即没有参数,并且第三个任务无返回值。

CompletableFuture<Void> future1=CompletableFuture.runAsync(()-> System.out.println("步骤1"),pool);CompletableFuture<Void> future2=CompletableFuture.runAsync(()->System.out.println("步骤2"),pool);CompletableFuture<Void> future3=future1.runAfterBothAsync(future2,()->System.out.println("步骤3"),pool);future3.join();

3、thenAcceptBothAsync:调用方为第一个任务的CompletionStage,第一个参数为第二个任务的CompletionStage。在第一个和第二个任务都执行完成后,开始执行第三个任务,第三个任务的参数分别为第一个、第二个任务的返回结果,并且第三个任务无返回值。

CompletableFuture<Integer> future1=CompletableFuture.supplyAsync(()->3,pool);CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->6,pool);CompletableFuture<Void> future3=future1.thenAcceptBothAsync(future2,(m,n)->{System.out.println(m);System.out.println(n);},pool);future3.join();

4、allOf:等待所有异步任务执行完成

CompletableFuture<Integer> future1=CompletableFuture.supplyAsync(()->3,pool);CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->6,pool);CompletableFuture<Integer> future3=CompletableFuture.supplyAsync(()->9,pool);CompletableFuture<Void> future4=CompletableFuture.allOf(future1,future2,future3);future4.join();System.out.println(future1.get());System.out.println(future2.get());System.out.println(future3.get());

五、异步任务的选择执行:
例如有三个任务,第三个任务需要在第一个任务和第二个任务中执行快的那一个执行完成后,才可以执行任务三
1、applyToEitherAsync:在任务一、任务二中,只要有一个任务先执行完成后,将执行快的那个任务的返回结果作为第三个任务的参数,然后才可执行任务三,并且任务三需要返回新的结果

CompletableFuture<Integer> future1=CompletableFuture.supplyAsync(()->{try {Thread.sleep(9000);return 3;} catch (InterruptedException e) {throw new RuntimeException(e);}},pool);CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->{try {Thread.sleep(6000);return 6;} catch (InterruptedException e) {throw new RuntimeException(e);}},pool);CompletableFuture<Integer> future3=future1.applyToEitherAsync(future2,v->v,pool);System.out.println(future3.get());

2、runAfterEitherAsync:在任务一、任务二中,只要有一个任务先执行完成后,再执行任务三,并且任务三无参数和返回值

CompletableFuture<Void> future1=CompletableFuture.runAsync(()->{try {Thread.sleep(3000);System.out.println("任务1");} catch (InterruptedException e) {throw new RuntimeException(e);}},pool);CompletableFuture<Void> future2=CompletableFuture.runAsync(()->{try {Thread.sleep(6000);System.out.println("任务2");} catch (InterruptedException e) {throw new RuntimeException(e);}},pool);CompletableFuture<Void> future3=future1.runAfterEitherAsync(future2,()-> System.out.println("任务3"),pool);System.out.println(future3.join());

3、acceptEitherAsync:在任务一、任务二中,只要有一个任务先执行完成后,将执行快的那一个任务的返回结果作为第三个任务的参数,然后才可执行任务三,并且任务三无需返回值

CompletableFuture<Integer> future1=CompletableFuture.supplyAsync(()->{try {Thread.sleep(3000);return 3;} catch (InterruptedException e) {throw new RuntimeException(e);}},pool);CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->{try {Thread.sleep(6000);return 6;} catch (InterruptedException e) {throw new RuntimeException(e);}},pool);CompletableFuture<Void> future3=future1.acceptEitherAsync(future2,v-> System.out.println(v),pool);System.out.println(future3.join());

这篇关于java 8 新特性CompletableFuture使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。