Java 8 - 并行调用异步方法并合并其结果
2022-09-04 01:42:49
我是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)