首页 > 其他分享 >CompleteFuture 学习

CompleteFuture 学习

时间:2024-08-19 16:38:00浏览次数:9  
标签:CompleteFuture 学习 other CompletableFuture action 执行 public fn

一 CompleteFuture 使用场景

  • 创建异步任务
  • 简单任务异步回调
  • 多任务组合处理

二 创建异步任务

  • supplyAsync (有返回值)
//使用默认线程池
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) 
//使用自定义线程池
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) 
  • runAsync(无返回值
//使用默认线程池
public static CompletableFuture<Void> runAsync(Runnable runnable)
//使用自定义线程池
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

三 任务异步回调

1. thenRun/thenRunAsync

上一个任务完成后执行

//不关心上一个任务执行返回结果
//thenRun 使用上一个任务的线程池
public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action,Executor executor)

2. thenAccept/thenAcceptAsync

第一个任务执行完成后,执行第二个回调方法任务,会将该任务的执行结果,作为入参,传递到回调方法中,但是回调方法是没有返回值的。

public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)

3. thenApply/thenApplyAsync

第一个任务执行完成后,执行第二个回调方法任务,会将该任务的执行结果,作为入参,传递到回调方法中,并且回调方法是有返回值的。

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)

4. exceptionally

某个任务执行异常时,执行的回调方法;并且有抛出异常作为参数,传递到回调方法

 public CompletableFuture<T> exceptionally(
        Function<Throwable, ? extends T> fn) {
        return uniExceptionallyStage(fn);
    }

5. whenComplete

某个任务执行完成后,执行的回调方法;并且whenComplete方法返回的CompletableFuture的result是上个任务的结果。

public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor)

6. handle

某个任务执行完成后,执行回调方法,并且是有返回值的;并且handle方法返回的CompletableFuture的result是回调方法执行的结果。

public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) 
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn)
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor)

测试Async

 public void testAsync() throws ExecutionException, InterruptedException, TimeoutException {
        //thenRun
        CompletableFuture.runAsync(()->{
            log.info(String.valueOf(System.currentTimeMillis()));
            //模拟任务执行,耗时10s
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("---thenRun---+++++++++++ 执行Task1 +++++++++++"+Thread.currentThread().getName());
                },executorConfig.ThreadPoolTaskExecutor()
        ).thenRun(()->{
            log.info("---thenRun---+++++++++++ Task1执行完成后执行Task2 +++++++++++"+Thread.currentThread().getName());
        });
        //thenAccept
        CompletableFuture.supplyAsync(()->{
            //模拟任务执行,耗时10s
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("---thenAccept---+++++++++++ 执行Task1并返回 +++++++++++"+Thread.currentThread().getName());
           return  "result of Task1";
        }).thenAccept((result)->{
            //Task1完成后,Task2接收到Task1的结果进行处理
            String resultUpperCase=result.toUpperCase();
            log.info("---thenAccept---Task2接收到Task1的结果并处理: "+resultUpperCase+Thread.currentThread().getName());
        });

        //thenApply
        CompletableFuture<Integer> apply = CompletableFuture.supplyAsync(() -> {
            log.info("---thenApply---+++++++++++ 执行Task1 +++++++++++"+Thread.currentThread().getName());
            //Task1执行完成后返回结果
            return 1;
        }, executorConfig.ThreadPoolTaskExecutor()).thenApply((r) -> {
            //接收Task1结果,处理并返回
            log.info("---thenApply--- Taks2收到Taks1结果处理后返回: "+ r);
            return r + 1;
        });
        //获取Task2最终返回结果
        int task2Result= apply.get(10, TimeUnit.SECONDS);
        System.out.println("获取到Task2的结果: "+task2Result);


    }

四 多任务组合处理

1 AND

将两个CompletableFuture组合起来,只有这两个都正常执行完了,才会执行某个任务。

  • thenCombine 会将两个任务的执行结果作为方法入参,传递到指定方法中,且有返回值
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn)
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn) 
public <U,V> CompletableFuture<V> thenCombineAsync( CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor)
  • thenAcceptBoth 会将两个任务的执行结果作为方法入参,传递到指定方法中,且无返回值
public <U> CompletableFuture<Void> thenAcceptBoth(
        CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)

public <U> CompletableFuture<Void> thenAcceptBothAsync(
        CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)

public <U> CompletableFuture<Void> thenAcceptBothAsync(
        CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action, Executor executor)
  • runAfterBoth 不会把执行结果当做方法入参,且没有返回值。
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
                                                Runnable action)

public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
                                                     Runnable action)

public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
                                                     Runnable action,
                                                     Executor executor)

2 OR

将两个CompletableFuture组合起来,只要其中一个执行完了,就会执行某个任务。

  • applyToEither:会将已经执行完成的任务,作为方法入参,传递到指定方法中,且有返回值
public <U> CompletableFuture<U> applyToEither(
        CompletionStage<? extends T> other, Function<? super T, U> fn)

public <U> CompletableFuture<U> applyToEitherAsync(
        CompletionStage<? extends T> other, Function<? super T, U> fn) 

public <U> CompletableFuture<U> applyToEitherAsync(
        CompletionStage<? extends T> other, Function<? super T, U> fn,
        Executor executor)
  • acceptEither: 会将已经执行完成的任务,作为方法入参,传递到指定方法中,且无返回值
public CompletableFuture<Void> acceptEither(
        CompletionStage<? extends T> other, Consumer<? super T> action)

public CompletableFuture<Void> acceptEitherAsync(
        CompletionStage<? extends T> other, Consumer<? super T> action)

public CompletableFuture<Void> acceptEitherAsync(
        CompletionStage<? extends T> other, Consumer<? super T> action,
        Executor executor)
  • runAfterEither: 不会把执行结果当做方法入参,且没有返回值。

3 AllOf

所有任务都执行完成后,才执行 allOf返回的CompletableFuture。如果任意一个任务异常,allOf的CompletableFuture,执行get方法,会抛出异常

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)

4 AnyOf

任意一个任务执行完,就执行anyOf返回的CompletableFuture。如果执行的任务异常,anyOf的CompletableFuture,执行get方法,会抛出异常

public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)

5 thenCompose

thenCompose方法会在某个任务执行完成后,将该任务的执行结果,作为方法入参,去执行指定的方法。该方法会返回一个新的CompletableFuture实例

public <U> CompletableFuture<U> thenCompose(
        Function<? super T, ? extends CompletionStage<U>> fn)

public <U> CompletableFuture<U> thenComposeAsync(
        Function<? super T, ? extends CompletionStage<U>> fn)

public <U> CompletableFuture<U> thenComposeAsync(
        Function<? super T, ? extends CompletionStage<U>> fn,
        Executor executor) 

refer https://juejin.cn/post/6970558076642394142

标签:CompleteFuture,学习,other,CompletableFuture,action,执行,public,fn
From: https://www.cnblogs.com/jinnandu/p/18367436

相关文章

  • java学习第八周
    临近开学,本周的任务完成情况不够好,平常乱七八糟的事情比较多,所以放在学习上的心思比较少。平均每天放在JAVA学习的时间约1个小时,放在编程的时间约半小时,解决问题的时间约1小时。下一个星期就要开学了,回看自己暑期的JAVA学习情况感觉比之前的暑期有很大的进步,在家中能拿出大量的时......
  • [Python学习日记-9] Python中的运算符
    简介        计算机可以进行的运算有很多种,但可不只加减乘除这么简单,运算按种类可分为算数运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、位运算,而本篇我们暂只介绍算数运算、比较运算、逻辑运算、赋值运算算数运算一、运算符描述        以下......
  • 【配电网】基于深度强化学习的有源配电网过流保护研究
    摘要本文旨在研究基于深度强化学习的有源配电网过流保护方法。传统配电网在实际运行中存在负荷数据损坏、缺失和误差等问题,可能导致过流保护失效。本文通过引入深度强化学习算法,提出一种智能化、动态化的过流保护策略,以应对有源配电网中的复杂过流问题。利用pandapower库创建......
  • HBase学习的第六天--Hbase之过滤器
    Hbase之过滤器HBase的基本API,包括增、删、改、查等。增、删都是相对简单的操作,与传统的RDBMS相比,这里的查询操作略显苍白,只能根据特性的行键进行查询(Get)或者根据行键的范围来查询(Scan)。HBase不仅提供了这些简单的查询,而且提供了更加高级的过滤器(Filter)来查询。过滤器可......
  • TypeScript学习之旅--编译选项
    本文简单聊一下TS文件的编译,以及TS编译的配置文件入门我们都知道TS文件需要先编译成js文件后才可以运行,编译TS文件可以在命令行执行  tsc ts文件名,得到对应的同名js文件,但每次改完代码后都需要重新执行编译,或者多个ts文件都需要多次编译,给我们的编码工作带来极大不便~编译......
  • HTML5+CSS3学习笔记补充——移动端网页+Bootstrap框架
    移动端网页和Bootstrap框架1.视口:用来约束HTML尺寸<!--视口标签是HTML骨架默认生成的设置网页宽度与逻辑分辨率(即设备)宽度一致--><metaname="viewport"content="width=device-width,initial-scale=1.0">2.二倍图:防止设计稿图片在高分辨率屏幕下模糊失真3.......
  • kafka学习
    kafka学习kafka应用场景Kafka入门实战教程(1)基础概念与术语-EdisonZhou-博客园(cnblogs.com)kafka设计kafka架构图架构图来源:一文带你搞懂Kafka的系统架构(深度好文,值得收藏)_kafka架构-CSDN博客kafka名词解释Broker:一台kafka服务器就是一个broker。一个集群由......
  • 2024年新版Python零基础从入门到进阶学习路线!
    Python基础初始Python基础语法流程控制-选择结构流程控制-循环结构字符串和正则函数入门函数高级数据结构-列表和元组数据结构-字典和集合IO和文件操作文件操作进阶面向对象入门面向对象三大特性面向对象应用异常处理常用内置模块序列化模块网络请求模块MySQL入门MySQL命......
  • 人工神经网络:竞争型学习
    Ciallo~(∠・ω<)⌒★我是赤川鹤鸣。这是我的第一篇关于人工智能技术的博客。内容大多数为本人的思考和学习笔记,希望对你有所帮助。现今,以反向传播为主的神经网络,在处理诸如分类任务时,通常由事先已经规定的分类来决定标签的分类数,进而确定网络架构。例如,如果我们对MNIST数......
  • linux学习记录(十)------进程间的通信(管道通信)
    文章目录1.IPC进程间通信常用的几种方式2.无名管道2.1.管道的概念2.2.管道的原理2.3管道的局限性2.4.创建匿名管道2.5.父子进程使用管道通信2.6.管道的读写行为2.7.查看管道缓冲区大小3.有名管道3.1.特点3.2.使用场景3.3.创建方式3.4.fifo文件可以使用io函数进程操作......