So I have this code that I want to run on new thread.
Let me explain better, I have 2 methods in which I want to run in parallel.
public String method1(){
ExecutorService pool = Executors.newSingleThreadExecutor();
return CompletableFuture.supplyAsync(() -> {
//...
}, pool);
}
public String method2(){
ExecutorService pool = Executors.newSingleThreadExecutor();
return CompletableFuture.supplyAsync(() -> {
//...
}, pool);
}
So I would like to call these two methods in another method & Run them in parallel.
public void method3(){
// Run both methods
method1();
method2();
// end
}
You method signature does not correspond to return value. When you change both methods to return CompletableFuture you can define expected behavior in method3
:
CompletableFuture<String> method1Future = method1();
CompletableFuture<String> method2Future = method2();
// example of expected behavior
method1Future.thenCombine(method2Future, (s1, s2) -> s1 + s2);
In the example above you will concatenate strings which are supplied asynchronously by method1
and method2
when both futures are completed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.