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

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick