所以我有这个代码,我想在新线程上运行。
让我更好地解释一下,我有两种方法可以并行运行。
public String method1(){
ExecutorService pool = Executors.newSingleThreadExecutor();
return CompletableFuture.supplyAsync(() -> {
//...
}, pool);
}
public String method2(){
ExecutorService pool = Executors.newSingleThreadExecutor();
return CompletableFuture.supplyAsync(() -> {
//...
}, pool);
}
所以我想用另一种方法称这两种方法。并行运行它们。
public void method3(){
// Run both methods
method1();
method2();
// end
}
答案 0 :(得分:1)
您的方法签名与返回值不对应。当您更改两个方法以返回CompletableFuture时,您可以在method3
中定义预期行为:
CompletableFuture<String> method1Future = method1();
CompletableFuture<String> method2Future = method2();
// example of expected behavior
method1Future.thenCombine(method2Future, (s1, s2) -> s1 + s2);
在上面的例子中,当两个期货都完成时,你将连接由method1
和method2
异步提供的字符串。