在completableFuture中多个thenApply

时间:2016-10-04 04:08:42

标签: completable-future

我有一种情况,我想在不同的线程中执行某些方法但想要将一个线程的结果传递给另一个线程。我班上有以下方法。

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()。我们有什么方法可以做到这一点?通过谷歌搜索并发现了一个有用的链接 - http://kennethjorgensen.com/blog/2016/introduction-to-completablefutures但是没有找到很多帮助。

1 个答案:

答案 0 :(得分:0)

您的代码段存在一些问题:

  1. 括号:您必须在结束之后开始下一个thenApply ,而不是substract方法之后。
  2. supplyAsync()是一种静态方法。按原样使用它。
  3. 如果您只想在上一次操作中打印出结果,请使用thenAccept代替thenApply
  4. 您无需在thenAccept中填写CF(您之前不必在thenApply内完成此操作。
  5. 这段代码编译,它可能接近你想要实现的目标:

        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();