CompletableFuture 提供非阻塞异步编程支持,可通过 supplyAsync/runAsync 创建任务,使用 thenApply/thenAccept/thenRun 处理结果,以 thenCompose/thenCombine 组合任务,用 allOf/anyOf 控制多任务,通过 exceptionally/handle/whenComplete 处理异常,结合自定义线程池优化资源管理,提升程序响应性与吞吐量。

在Java中,CompletableFuture 是实现异步编程的重要工具,它提供了对 Future 的增强支持,允许以非阻塞方式执行任务,并通过回调机制处理结果或异常。相比传统的 Future,CompletableFuture 支持链式调用、组合多个异步任务以及更灵活的错误处理。
创建异步任务
你可以使用 CompletableFuture.supplyAsync() 或 runAsync() 来启动一个异步任务:
- supplyAsync:用于有返回值的任务,接收一个 Supplier 函数式接口。
- runAsync:用于无返回值的任务,接收一个 Runnable 接口。
示例:
CompletableFuture// 模拟耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Hello from async";
});
你也可以传入自定义线程池来控制资源:
立即学习“Java免费学习笔记(深入)”;
ExecutorService executor = Executors.newFixedThreadPool(4);CompletableFuture
return "Task executed in custom pool";
}, executor);
处理结果和回调
使用 thenApply、thenAccept、thenRun 等方法可以在任务完成后执行后续操作:
- thenApply:接收上一步的结果并返回新的结果。
- thenAccept:消费结果但不返回值。
- thenRun:不关心结果,只运行一段逻辑。
示例:
future.thenApply(result -> result + " processed").thenAccept(System.out::println)
.thenRun(() -> System.out.println("Done"));
组合多个异步任务
CompletableFuture 提供了多种方式组合多个异步操作:
大小仅1兆左右 ,足够轻便的商城系统; 易部署,上传空间即可用,安全,稳定; 容易操作,登陆后台就可设置装饰网站; 并且使用异步技术处理网站数据,表现更具美感。 前台呈现页面,兼容主流浏览器,DIV+CSS页面设计; 如果您有一定的网页设计基础,还可以进行简易的样式修改,二次开发, 发布新样式,调整网站结构,只需修改css目录中的css.css文件即可。 商城网站完全独立,网站源码随时可供您下载
- thenCompose:用于串行组合两个依赖的任务(类似 flatMap)。
- thenCombine:并行执行两个任务,并合并结果。
- allOf 和 anyOf:等待多个任务完成。
串行任务示例:
CompletableFutureCompletableFuture
CompletableFuture.supplyAsync(() -> result + " -> Result2")
);
并行合并结果:
CompletableFutureCompletableFuture
task1.thenCombine(task2, (a, b) -> a + b).thenAccept(System.out::println); // 输出 AB
等待所有任务完成:
CompletableFutureall.thenRun(() -> System.out.println("All tasks finished"));
异常处理
异步任务中可能发生异常,CompletableFuture 提供了专门的异常处理方法:
- exceptionally:捕获异常并提供默认值。
- handle:无论是否发生异常都会执行,可用于统一处理结果和异常。
- whenComplete:类似 handle,但不能修改结果,仅用于监听。
示例:
CompletableFuture.supplyAsync(() -> {throw new RuntimeException("Oops!");
}).exceptionally(ex -> {
System.err.println("Error: " + ex.getMessage());
return "Fallback Value";
}).thenAccept(System.out::println);
基本上就这些。CompletableFuture 让 Java 的异步编程变得直观且强大,合理使用可以显著提升程序响应性和吞吐量,尤其是在 I/O 密集型或远程调用场景中。注意避免阻塞主线程(如不必要的 get() 调用),并记得关闭自定义线程池。









