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 future = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return “Hello from async”;
});
你也可以传入自定义线程池来控制资源:
立即学习“Java免费学习笔记(深入)”;
ExecutorService executor = Executors.newFixedThreadPool(4);
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
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 提供了多种方式组合多个异步操作:
thenCompose:用于串行组合两个依赖的任务(类似 flatMap)。 thenCombine:并行执行两个任务,并合并结果。 allOf 和 anyOf:等待多个任务完成。
串行任务示例:
CompletableFuture step1 = CompletableFuture.supplyAsync(() -> “Result1”);
CompletableFuture step2 = step1.thenCompose(result ->
CompletableFuture.supplyAsync(() -> result + ” -> Result2″)
);
并行合并结果:
CompletableFuture task1 = CompletableFuture.supplyAsync(() -> “A”);
CompletableFuture task2 = CompletableFuture.supplyAsync(() -> “B”);
task1.thenCombine(task2, (a, b) -> a + b).thenAccept(System.out::println); // 输出 AB
等待所有任务完成:
CompletableFuture all = CompletableFuture.allOf(task1, task2);
all.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() 调用),并记得关闭自定义线程池。
以上就是Java中如何使用CompletableFuture实现异步处理的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/202547.html
微信扫一扫
支付宝扫一扫