如何在新线程上并行运行CompletableFuture

问题描述 投票:1回答:1

所以我有这个代码,我想在新线程上运行。

让我解释一下,我有两种方法可以并行运行。

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
}
java multithreading completable-future
1个回答
1
投票

方法签名与返回值不对应。当您更改两个方法以返回CompletableFuture时,您可以在method3中定义预期行为:

CompletableFuture<String> method1Future = method1();
CompletableFuture<String> method2Future = method2();

// example of expected behavior
method1Future.thenCombine(method2Future, (s1, s2) -> s1 + s2);

在上面的例子中,当两个期货都完成时,你将连接由method1method2异步提供的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.