gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:21:45 25 4
gpt4 key购买 nike

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

让我更好地解释一下,我想并行运行两种方法。

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
}

最佳答案

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

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

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

在上面的示例中,当两个 future 都完成时,您将连接由 method1method2 异步提供的字符串。

关于java - 如何在新线程上并行运行 CompletableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48009312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com