Executor 框架管理线程池,使您能够提交任务而不是手动创建线程,CompletableFuture 以声明方式组合异步操作。它们一起是 Java 中执行并发/异步工作的现代方式——避免了原始线程管理的成本和复杂性。
原始线程的问题
java
(Task t : tasks) {
(() -> process(t)).start();
}
// ✅ a fixed pool reuses a bounded set of threads for many tasks
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Integer> future = executor.submit(() -> compute()); // submit a task
Integer result = future.get(); // blocks until the result is ready
executor.shutdown(); // stop accepting tasks; let running ones finish
ExecutorService 将做什么(任务)与如何做(线程管理)分离——它重用一个有限的线程池,防止资源耗尽和持续创建线程的开销。
Future<Integer> f = executor.submit(task);
f.get(); // ❌ BLOCKS the calling thread; can't chain/combine without blocking
Future.get() 会阻塞,你无法轻松链接依赖操作或组合结果——这正是 CompletableFuture 要解决的问题。
CompletableFuture.supplyAsync(() -> fetchUser(id)) // run async, returns a value
.thenApply(user -> user.getName()) // transform the result (non-blocking)
.thenApply(String::toUpperCase)
.thenAccept(name -> System.out.println(name)) // consume the final result
.exceptionally(ex -> { log(ex); return null; }); // handle errors in the chain
CompletableFuture 让你构建非阻塞管道——转换(thenApply)、链接依赖的异步调用(thenCompose)和处理错误(exceptionally)——而无需阻塞线程。
// run two independent async calls in PARALLEL and combine their results
CompletableFuture<User> userF = CompletableFuture.supplyAsync(() -> fetchUser(id));
CompletableFuture<Order> orderF = CompletableFuture.supplyAsync(() -> fetchOrder(id));
userF.thenCombine(orderF, (user, order) -> buildProfile(user, order))
.thenAccept(profile -> render(profile));
// wait for many to complete
CompletableFuture.allOf(f1, f2, f3).join(); // all done
thenCombine、allOf 和 anyOf 优雅地协调多个异步任务——并行运行独立工作并组合结果。
Executor 框架和 CompletableFuture 是 Java 中处理并发和异步工作的现代、正确方式,取代了容易出错的手动线程管理。
线程池(ExecutorService)避免了资源耗尽和为每个任务创建一个线程的开销——这对可扩展的服务器至关重要。
CompletableFuture 通过启用可组合、非阻塞管道来解决 Future 的阻塞限制,这些管道以声明方式链接、转换、组合和错误处理异步操作——对于必须协调许多并发调用(数据库、API、微服务)的高效 I/O 密集服务至关重要。
理解这些概念(而不是原始线程和阻塞 Future)是构建高性能、可扩展的并发 Java 应用程序的基础,也是高级水平的关键能力。