article/java/CompletableFuture.md
2025-01-06 14:27:10 +08:00

5.2 KiB
Raw Blame History

CompletableFuture API

以下是 CompletableFuture API 名字、说明和示例的表格整理:

API 名称 说明 示例
supplyAsync(Supplier<U> supplier) 异步执行任务,返回计算结果。 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100);
runAsync(Runnable runnable) 异步执行没有返回值的任务。 CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { /* 执行某些任务 */ });
get() 阻塞当前线程,直到任务完成并返回计算结果。 Integer result = future.get();
get(long timeout, TimeUnit unit) 阻塞当前线程,最多等待指定时间来获取结果,超时抛出 TimeoutException Integer result = future.get(1, TimeUnit.SECONDS);
thenApply(Function<T, U> fn) 在任务完成后应用函数 fn 来处理计算结果,并返回一个新的 CompletableFuture CompletableFuture<Integer> future2 = future.thenApply(result -> result * 2);
thenAccept(Consumer<T> action) 在任务完成后执行 action,但不返回任何结果。 future.thenAccept(result -> System.out.println("结果是: " + result));
thenRun(Runnable action) 在任务完成后执行没有输入输出的 Runnable 操作。 future.thenRun(() -> System.out.println("任务完成"));
thenCombine(CompletableFuture<U> other, BiFunction<T, U, V> fn) 当两个 CompletableFuture 都完成时,合并它们的结果,返回一个新的 CompletableFuture CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);
thenCompose(Function<T, CompletableFuture<U>> fn) 返回一个新的 CompletableFuture,执行链式的异步任务。 CompletableFuture<Integer> future3 = future.thenCompose(result -> CompletableFuture.supplyAsync(() -> result * 2));
exceptionally(Function<Throwable, T> fn) 当任务执行失败时,执行异常处理,并返回一个默认值。 future.exceptionally(ex -> { System.out.println("任务异常: " + ex.getMessage()); return -1; });
handle(BiFunction<T, Throwable, T> fn) 无论任务成功还是失败,都处理结果或异常,并返回一个新的结果。 future.handle((result, ex) -> { if (ex != null) return -1; return result * 2; });
CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) 不改变结果 适合监听日志 处理异常 future.whenComplete((result, ex) -> { if (ex == null) { System.out.println("结果: " + result); } else { System.err.println("异常: " + ex.getMessage()); }});
allOf(CompletableFuture<?>... futures) 等待所有 CompletableFuture 完成,返回一个新的 CompletableFuture<Void> CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(future1, future2);
anyOf(CompletableFuture<?>... futures) 等待任意一个 CompletableFuture 完成,返回一个新的 CompletableFuture<Object> CompletableFuture<Object> anyOfFuture = CompletableFuture.anyOf(future1, future2);
cancel(boolean mayInterruptIfRunning) 取消任务。如果任务还未开始,取消会返回 true;如果任务已开始,mayInterruptIfRunningtrue 时可以中断任务。 future.cancel(true);
join() 阻塞并等待任务完成,类似于 get(),但不会抛出 ExecutionException,而是抛出 CompletionException Integer result = future.join();

简要说明:

  • supplyAsyncrunAsync 用于异步执行任务,分别支持返回结果和无返回值的任务。
  • get()join() 用于等待异步计算结果,get() 可能抛出 ExecutionExceptionjoin() 会抛出 CompletionException
  • thenApplythenAcceptthenRunthenCombine 等方法用于在任务完成后进行链式处理,可以处理计算结果或执行后续任务。
  • exceptionallyhandle 用于处理任务中的异常。
  • allOfanyOf 用于组合多个 CompletableFuture,前者等待所有任务完成,后者等待任意一个完成。

这种 API 使得异步编程更加简洁,同时避免了传统回调地狱的问题。