CompletableFuture 提供了比传统 Future 更强大的异步编程能力,支持链式调用、任务组合与异常处理;通过 supplyAsync 和 runAsync 可创建异步任务,默认使用公共线程池,也可指定自定义线程池;thenApply、thenAccept、thenRun 实现任务的链式处理;thenCompose 用于串行化依赖任务,thenCombine 合并两个并行任务结果;exceptionally 和 handle 方法用于异常捕获与恢复,提升异步代码的健壮性与可读性。

在Java中,CompletableFuture 是处理异步编程的强大工具。它实现了 Future 和 CompletionStage 接口,支持链式调用、组合多个异步任务,并能更好地处理异常和回调。相比传统的 Future,CompletableFuture 提供了更灵活的非阻塞操作方式。
你可以使用 CompletableFuture.supplyAsync() 或 runAsync() 来启动一个异步任务:
示例:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
try { Thread.sleep(1000); } catch (InterruptedException e) {}
return "Hello from async";
});
<p>// 获取结果(不推荐阻塞,仅演示)
String result = future.get(); // 输出: Hello from async</p>默认使用 ForkJoinPool.commonPool() 执行任务,也可以传入自定义线程池:
立即学习“Java免费学习笔记(深入)”;
ExecutorService executor = Executors.newFixedThreadPool(4);
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Task executed in custom thread pool";
}, executor);
CompletableFuture 支持在任务完成后执行后续操作:
示例:
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println) // 输出: Hello World
.thenRun(() -> System.out.println("Done"));
可以将多个异步任务组合起来:
示例 - thenCompose(一个任务依赖另一个的结果):
CompletableFuture<String> combined = CompletableFuture
.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " Java"));
<p>combined.thenAccept(System.out::println); // 输出: Hello Java</p>示例 - thenCombine(并行执行并合并):
CompletableFuture<String> part1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> part2 = CompletableFuture.supplyAsync(() -> "World"); <p>part1.thenCombine(part2, (a, b) -> a + " " + b) .thenAccept(System.out::println); // 输出: Hello World</p>
异步任务中发生异常不会自动抛出,需显式处理:
示例:
CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Oops!");
})
.exceptionally(ex -> {
System.out.println("Error: " + ex.getMessage());
return "Fallback Value";
})
.thenAccept(System.out::println); // 输出: Fallback Value
使用 handle 的方式:
CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException("Boom!");
return "Success";
}).handle((result, throwable) -> {
if (throwable != null) {
return "Handled error: " + throwable.getMessage();
}
return result;
}).thenAccept(System.out::println);
基本上就这些。CompletableFuture 让 Java 的异步编程变得清晰且可控,合理使用可以显著提升程序响应性和吞吐量。
以上就是如何在Java中使用CompletableFuture处理异步任务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号