gpt4 book ai didi

Java 8 - 并行调用异步方法并合并它们的结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:20 25 4
gpt4 key购买 nike

我是 Java 8 并发特性(例如 CompletableFuture)的新手,希望您能帮助我开始使用以下用例。

有一个名为 TimeConsumingServices 的服务,它提供耗时的操作,我想并行运行这些操作,因为它们都是独立的。

interface TimeConsumingService {

default String hello(String name) {
System.out.println(System.currentTimeMillis() + " > hello " + name);
return "Hello " + name;
}
default String planet(String name) {
System.out.println(System.currentTimeMillis() + " > planet " + name);
return "Planet: " + name;
}
default String echo(String name) {
System.out.println(System.currentTimeMillis() + " > echo " + name);
return name;
}

default byte[] convert(String hello, String planet, String echo) {
StringBuilder sb = new StringBuilder();
sb.append(hello);
sb.append(planet);
sb.append(echo);
return sb.toString().getBytes();
}
}

到目前为止,我实现了以下示例,并且成功地并行调用了所有三个服务方法。

public class Runner implements TimeConsumingService {

public static void main(String[] args) {
new Runner().doStuffAsync();
}

public void doStuffAsync() {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> this.hello("Friend"));
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> this.planet("Earth"));
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> this.echo("Where is my echo?"));

CompletableFuture.allOf(future1, future2, future3).join();
}
}

有没有办法收集每个服务调用的返回值并调用byte[]‘convert(String, String, String)方法?

最佳答案

要在返回所有结果后合并结果,您可以这样做

CompletableFuture<byte[]> byteFuture = CompletableFuture.allOf(cf1, cf2, cf3)
.thenApplyAsync(aVoid -> convert(cf1.join(), cf2.join(), cf3.join()));
byte[] bytes = byteFuture.join();

这将运行您所有的 future ,等待它们全部完成,然后在它们全部完成后立即调用您提到的 convert 方法。

关于Java 8 - 并行调用异步方法并合并它们的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42504277/

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