多个 thenApply 在一个 completableFuture 中

Multiple thenApply in a completableFuture

我有一种情况,我想在不同的线程中执行一些方法,但又想将一个线程的结果传递给另一个线程。我的 class.

中有以下方法
public static int addition(int a, int b){
    System.out.println((a+b));
    return (a+b);
}

public static int subtract(int a, int b){
    System.out.println((a-b));
    return (a-b);
}

public static int multiply(int a, int b){
    System.out.println((a*b));
    return (a*b);
}
public static String convert(Integer a){
    System.out.println((a));
    return a.toString();
}

这里是主要方法:

public static void main(String[] args) {
    int a = 10;
    int b = 5;
    CompletableFuture<String> cf = new CompletableFuture<>();
    cf.supplyAsync(() -> addition(a, b))
        .thenApply(r ->subtract(20,r)
                .thenApply(r1 ->multiply(r1, 10))
                .thenApply(r2 ->convert(r2))
                .thenApply(finalResult ->{
                    System.out.println(cf.complete(finalResult));
                }));
    System.out.println(cf.complete("Done"));

}

我正在尝试将加减乘法的结果传递给打印结果。但我收到编译错误。看起来我们不能做嵌套的 thenApply()。我们有什么办法可以做到这一点?搜索了 google 并找到了一个有用的 link- http://kennethjorgensen.com/blog/2016/introduction-to-completablefutures 但没有找到太多帮助。

您的代码段有几处错误:

  1. 括号:你要开始下一个thenApply after前一个的结束,而不是在substract方法之后。
  2. supplyAsync() 是一个静态方法。照原样使用它。
  3. 如果只想打印出上次操作的结果,使用thenAccept代替thenApply
  4. 您不需要在 thenAccept 完成 CF(之前在 thenApply 也不需要完成。

这段代码通过编译,它可能接近你想要实现的目标:

    CompletableFuture<Void> cf = CompletableFuture
        .supplyAsync(() -> addition(a, b))
        .thenApply(r -> subtract(20, r))
        .thenApply(r1 -> multiply(r1, 10))
        .thenApply(r2 -> convert(r2))
        .thenAccept(finalResult -> {
            System.out.println("this is the final result: " + finalResult);
        });

    //just to wait until the cf is completed - do not use it on your program
    cf.join();