有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java CompletableFuture:如何将一个函数应用于多个CompletableFuture?

假设我有3个下载,框架为completable futures:

    CompletableFuture<Doc> dl1 = CompletableFuture.supplyAsync(() -> download("file1"));
    CompletableFuture<Doc> dl2 = CompletableFuture.supplyAsync(() -> download("file2"));
    CompletableFuture<Doc> dl3 = CompletableFuture.supplyAsync(() -> download("file3"));

然后,所有这些都需要以相同的方式处理

    CompletableFuture<String> s1 = dl1.thenApply(Doc::getFilename);
    CompletableFuture<String> s2 = dl2.thenApply(Doc::getFilename);
    CompletableFuture<String> s3 = dl3.thenApply(Doc::getFilename);

你可以想象应用多个函数,都是并行的

根据干燥原理,这个例子似乎不合适。因此,我正在寻找一种解决方案,只定义一个并行执行3次的工作流

如何做到这一点

我尝试了allOf,但有两个问题:1)它开始阻塞,2)返回类型只能run填充而不能处理它


共 (1) 个答案

  1. # 1 楼答案

    Stream.of("file1", "file2", "file3") // or your input in any other format, that can easily be transformed to a stream...
          // .parallel() // well... depends...
          .map(s -> CompletableFuture.supplyAsync(() -> download(s)))
          .map(dl -> dl.thenApply(Doc::getFilename))
          .map(CompletableFuture::join) // if you want to have all the results collected
          .collect(Collectors.toList());
    

    当然,这两个map调用也可以组合使用。但至少你不会把每件事都写x遍。。。如果你不喜欢集合List,你也可以在它上面调用其他东西,例如.forEach(System.out::println)。{}的好处是,一旦响应可用,就会调用消费者

    或者经典:只需为输入使用一个循环和一个列表/数组,但您可能需要处理比流更多的内容