Java并发编程中CompletableFuture使用方法

CompletableFuture 提供非阻塞异步编程能力,支持链式调用组合任务。1. 用 runAsync/supplyAsync 创建异步任务,可指定线程池;2. thenApply/thenAccept/thenRun 实现结果处理;3. thenCompose 串行组合任务,thenCombine 并行合并结果;4. exceptionally/handle 进行异常处理;5. allOf/anyOf 协调多个任务同步。合理使用可提升代码可读性与健壮性,适用于 I/O 密集型场景。

在Java并发编程中,CompletableFuture 是对 Future 的增强,提供了非阻塞、函数式、可编排的异步编程能力。它允许你以链式调用的方式组合多个异步任务,避免回调地狱,提升代码可读性和维护性。

1. 创建 CompletableFuture 任务

你可以通过静态方法创建一个异步任务:

  • runAsync():执行无返回值的任务
  • supplyAsync():执行有返回值的任务

默认使用 ForkJoinPool.commonPool() 线程池,也可以传入自定义线程池:

CompletableFuture run = CompletableFuture.runAsync(() -> {
    System.out.println("执行无返回任务");
});

CompletableFuture supply = CompletableFuture.supplyAsync(() -> { return "Hello from async"; }, Executors.newFixedThreadPool(2));

2. 任务完成后处理结果(thenApply, thenAccept, thenRun)

当异步任务完成时,可以进行后续操作:

  • thenApply(Function):转换结果并返回新值
  • thenAccept(Consumer):消费结果,无返回
  • thenRun(Runnable):不关心结果,只运行后续逻辑
CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hi");

future.thenApply(s -> s + " World") .thenAccept(System.out::println) .thenRun(() -> System.out.println("完成"));

3. 组合多个异步任务(thenCompose, thenCombine)

当你需要合并多个异步操作时,这两个方法非常有用:

  • thenCompose:串行组合,前一个任务的结果用于下一个任务(类似 flatMap)
  • thenCombine:并行组合,两个任务都完成后合并结果
// 串行:先获取用户,再获取订单
CompletableFuture getUser = CompletableFuture.supplyAsync(() -> new User("Alice"));
CompletableFuture getOrder = getUser.thenCompose(user ->
    CompletableFuture.supplyAsync(() -> new Order(user.getName()))
);

// 并行:同时获取价格和折扣,然后合并 CompletableFuture price = CompletableFuture.supplyAsync(() -> 100.0); CompletableFuture discount = CompletableFuture.supplyAsync(() -> 0.9); CompletableFuture finalPrice = price.thenCombine(discount, (p, d) -> p * d);

4. 异常处理(handle, exceptionally)

异步任务可能出错,CompletableFuture 提供了异常处理机制:

  • exceptionally(Function):仅处理异常,返回默认值
  • handle(BiFunction):无论是否异常都会执行,可统一处理结果和异常
CompletableFuture broken = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了");
});

broken.exceptionally(ex -> "默认值") .thenAccept(System.out::println);

// 或者用 handle broken.handle((result, ex) -> { if (ex != null) { System.out.println("捕获异常: " + ex.getMessage()); return "恢复结果"; } return result; });

5. 等待多个任务完成(allOf, anyOf)

当你需要协调多个异步任务时:

  • CompletableFuture.allOf(...):所有任务都完成才算完成,返回 void
  • CompletableFuture.anyOf(...):任意一个完成即完成
CompletableFuture f1 = CompletableFuture.supplyAsync(() -> "A");
CompletableFuture f2 = CompletableFuture.supplyAsync(() -> "B");
CompletableFuture f3 = CompletableFuture.supplyAsync(() -> "C");

CompletableFuture all = CompletableFuture.allOf(f1, f2, f3); all.thenRun(() -> { System.out.println("全部完成"); try { System.out.println(f1.get()); // 获取结果 } catch (Exception e) { } });

基本上就这些核心用法。合理使用 CompletableFuture 能让你的异步代码更清晰、更健壮,尤其适合 I/O 密集型或远程调用场景。关键是理解每个方法的返回类型和执行时机,避免阻塞主线程。