Multiple thenApply in a completableFuture

梦想与她 提交于 2019-12-08 09:06:39

问题


I have a situation where I want to execute some methods in different threads but want to pass the result of one thread to another. I have following methods in my 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();
}

here is main method:

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

}

I am trying to pass result of addition to subtraction to multiplication to printing result. But I am getting compilation error. Looks like we can't do nested thenApply(). Is there any way we can do this? Searched it over google and found one helpful link- http://kennethjorgensen.com/blog/2016/introduction-to-completablefutures But didn't find much help.


回答1:


A couple of things are wrong with your snippet:

  1. Parenthesis: you have to start the next thenApply after the end of the one before, not after the substract method.
  2. supplyAsync() is a static method. Use it as such.
  3. If you just want to print out the result in the last operation, use thenAccept instead of thenApply
  4. You do not need to complete the CF in thenAccept (neither you would have to do it in thenApply before.

This piece of code compiles, and it may be close to what you want to achieve:

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


来源:https://stackoverflow.com/questions/39844016/multiple-thenapply-in-a-completablefuture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!