0

我想使用CompletableFuture异步供应商运行下面发布的三种方法,这样,当 Executor 完成时,Futurelist应该分别包含从这三种方法返回的三个值。我知道如何使用Futurelist,例如:

futureList = CompletableFuture.supplyAsync()

但就我而言,我想要类似的东西:

futureList.add(CompletableFuture.supplyAsync())

请让我知道我该怎么做。

方法

this.compStabilityMeasure(this.frameIjList, this.frameIkList, SysConsts.STABILITY_MEASURE_TOKEN);
this.setTrackingRepValue(this.compTrackingRep(this.frameIjList, this.frameIkList, SysConsts.TRACKING_REPEATABILITY_TOKEN));
this.setViewPntRepValue(this.compViewPntRep(this.frameIjList, this.frameIkList, SysConsts.VIEWPOINT_REPEATABILITY_TOKEN));

compStabilityMeasure 方法实现

private void compStabilityMeasure(ArrayList<Mat> frameIjList, ArrayList<Mat>   
frameIkList, String token) throws InterruptedException, ExecutionException {
    // TODO Auto-generated method stub
    synchronized (frameIjList) {
        synchronized (frameIjList) {
            this.setRepValue(this.compRep(frameIjList, frameIkList, token));
            this.setSymRepValue(this.compSymRep(this.getRepValue(), frameIkList, frameIjList, token));
        }
    }
}
4

2 回答 2

0

你想看看使用“thenCombineAsync”,例如:

    CompletableFuture<String> firstFuture = firstMethod();
    CompletableFuture<String> secondFuture = secondMethod();
    CompletableFuture<String> thirdFuture = thirdMethod();
    CompletableFuture<List<String>> allCompleted = firstFuture
            .thenCombineAsync(secondFuture, (first, second) -> listOf(first, second))
            .thenCombineAsync(thirdFuture, (list, third) -> {
                list.add(third);
                return list;
            });
于 2015-07-08T10:37:18.110 回答
0

您可以使用allOf,然后创建一个CompletableFuture使用包含您的个人 CompletableFutures 结果的 Stream 完成的:

CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "hi1");
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> "hi2");

List<CompletableFuture<String>> cfsList = Arrays.asList(cf1, cf2);
CompletableFuture<Void> allCfs = CompletableFuture.allOf((CompletableFuture<String>[]) cfsList.toArray());
CompletableFuture<Stream<String>> cfWithFinishedStream = allCfs.thenApply((allCf) -> 
              cfsList.stream().map(cf -> cf.getNow("")));

CF 完成时从流中获取值的示例:

    cfWithFinishedStream.thenAccept(stream -> 
           stream.forEach(string -> System.out.println(string)));

如果您不喜欢流,可以使用 collect 将它们转换为 List:

    CompletableFuture<List<String>> cfWithFinishedList = allCfs
            .thenApply((allCf) -> 
              cfsList.stream().map(cf -> 
                       cf.getNow("")).collect(Collectors.toList()));
于 2015-07-11T14:27:05.910 回答