【发布时间】:2017-02-28 09:01:33
【问题描述】:
我是 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)?
【问题讨论】:
标签: java asynchronous java-8