Java 8-调用方法并行异步并组合其结果 [英] Java 8 - Call methods async in parallel and combine their results

查看:79
本文介绍了Java 8-调用方法并行异步并组合其结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to the Java 8 concurrency features such as CompletableFuture and I hope you can help to get started with the following use case.

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

There is a service called TimeConsumingServices that provides time consuming operations which I'd like to run in parallel since all of them are independent.

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();
  }
}

到目前为止,我已经实现了以下示例,并且设法并行调用了所有三个服务方法.

So far I implemented the following example and I have managed to call all three service methods in parallel.

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)?

Is there a way to collect the return values of each service call and invoke the method byte[]‘ convert(String, String, String)?

推荐答案

要在返回结果后合并结果,可以执行以下操作

To combine the result after you have returned them all you can do something like this

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

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

This will run all of your futures, wait for them all to complete, then as soon as they are all finished will call your convert method you mention.

这篇关于Java 8-调用方法并行异步并组合其结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆