You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java将三个CompletableFuture合并为一个?

使用CompletableFuture.allOf()处理多异步结果的正确实现

你可以通过CompletableFuture.allOf()等待三个异步任务全部完成,之后统一获取每个任务的结果并解析出需要的列表。下面是具体实现代码:

// 定义三个异步任务
CompletableFuture<JsonObject> futureProducts = entityService.getProducts();
CompletableFuture<JsonObject> futureCustomers = entityService.getCustomers();
CompletableFuture<JsonObject> futureOrders = entityService.getOrders();

// 使用allOf()等待所有任务完成
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futureProducts, futureCustomers, futureOrders);

// 所有任务完成后执行依赖逻辑
allFutures.thenAccept(v -> {
    try {
        // 解析每个任务结果中的value列表
        JsonArray products = futureProducts.get().getJsonArray("value");
        JsonArray customers = futureCustomers.get().getJsonArray("value");
        JsonArray orders = futureOrders.get().getJsonArray("value");

        // 在这里编写依赖这三个列表的后续业务代码
        // 示例:processCombinedData(products, customers, orders);
    } catch (InterruptedException | ExecutionException e) {
        // 处理异步任务抛出的异常
        e.printStackTrace();
        // 可根据业务需求添加兜底逻辑
    }
}).exceptionally(e -> {
    // 处理全局异常
    e.printStackTrace();
    return null;
});

核心要点

  • allOf()仅负责等待所有任务完成,不返回任务结果,因此需要单独调用每个Future的get()方法获取结果(此时因allOf已完成等待,get()不会阻塞)。
  • 必须处理get()可能抛出的中断异常和执行异常,避免未捕获异常导致程序异常终止。
  • 若后续逻辑需要返回结果,可将thenAccept()替换为thenApply(),并返回处理后的结果对象。

内容的提问来源于stack exchange,提问作者Blake Rivell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:04:58