问题
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:
- Parenthesis: you have to start the next
thenApply
after the end of the one before, not after thesubstract
method. supplyAsync()
is a static method. Use it as such.- If you just want to print out the result in the last operation, use
thenAccept
instead ofthenApply
- You do not need to complete the CF in
thenAccept
(neither you would have to do it inthenApply
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