CompletableFuture是Java异步编程核心,支持非阻塞任务与链式编排。使用supplyAsync/runAsync创建异步任务,可指定自定义线程池;通过thenApply/thenAccept/thenRun实现顺序调用;用thenCombine/allOf/anyOf组合多个任务;借助exceptionally/handle处理异常,提升代码清晰度与执行效率。

在Java中,CompletableFuture 是处理异步编程的核心工具之一。它不仅支持非阻塞的任务执行,还能通过链式调用组合多个异步操作,提升程序的响应性和吞吐量。掌握其应用技巧,能有效简化复杂异步逻辑的编写。
创建异步任务
使用 CompletableFuture.supplyAsync() 或 runAsync() 可以启动异步任务。前者用于有返回值的场景,后者适用于无返回值的操作。
-
supplyAsync 接受一个 Supplier 函数,返回 CompletableFuture
-
runAsync 接受 Runnable,返回 CompletableFuture
- 可指定自定义线程池,避免阻塞ForkJoinPool公共池
示例:
CompletableFuturefuture = CompletableFuture.supplyAsync(() -> { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) {} return "Hello from async"; }, Executors.newFixedThreadPool(2));
任务编排与链式调用
通过 thenApply、thenAccept、thenRun 等方法,可以实现任务的顺序执行和结果传递。
立即学习“Java免费学习笔记(深入)”;
- thenApply:转换上一阶段的结果,返回新的值
- thenAccept:消费结果,不返回值
- thenRun:仅在前阶段完成后执行动作,不依赖结果
示例:
CompletableFutureresult = CompletableFuture .supplyAsync(() -> "fetch data") .thenApply(data -> data + " processed") .thenApply(processed -> processed.toUpperCase());
组合多个异步任务
当需要并行执行多个任务并合并结果时,可以使用 thenCombine、allOf 或 anyOf。
- thenCombine:合并两个异步任务的结果
-
allOf:等待所有任务完成,返回 CompletableFuture
- anyOf:任一任务完成即触发回调
示例(合并两个请求):
CompletableFuturetask1 = CompletableFuture.supplyAsync(() -> "result1"); CompletableFuture task2 = CompletableFuture.supplyAsync(() -> "result2"); CompletableFuture combined = task1.thenCombine(task2, (r1, r2) -> r1 + " " + r2);
异常处理机制
异步任务中的异常不会自动抛出,必须通过 exceptionally 或 handle 显式处理。
- exceptionally:捕获异常并提供默认值
- handle:无论成功或失败都执行,可用于统一处理结果和异常
示例:
CompletableFuturesafeFuture = CompletableFuture .supplyAsync(() -> { if (Math.random() > 0.5) throw new RuntimeException("Error!"); return "success"; }) .exceptionally(ex -> "fallback value");
基本上就这些。合理使用 CompletableFuture 能让异步代码更清晰、高效,关键是理解各阶段方法的行为差异,并注意线程资源管理。不复杂但容易忽略。










