介绍
java.util.concurrent.CompletionStage
public interface CompletionStage<T>
java.util.concurrent.CompletableFuture
的父接口
API
注意事项:
- 所有方法都有类似的 xxAsync 以及重载,只详细列一下
thenApply
,其他不列出来 - 有无返回值,可以通过看函数类型
处理单个 Future
- thenApply , thenApplyAsync
<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
<U> CompletionStage<U> thenApplyAsync (Function<? super T,? extends U> fn);
- 异步执行,使用
ForkJoinPool.commonPool()
线程池
- 异步执行,使用
<U> CompletionStage<U> thenApplyAsync (Function<? super T,? extends U> fn, Executor executor);
- 异步执行,指定线程池
- thenAccept
CompletionStage<Void> thenAccept(Consumer<? super T> action);
- thenRun
CompletionStage<Void> thenRun(Runnable action);
- thenCompose
- CompletionStage thenCompose (Function<? super T, ? extends CompletionStage> fn);
- 对结果调用函数并执行返回的 future
Function
的入参是自身的执行结果,出参是另一个CompletionStage
结果和异常处理
- handle
<U> CompletionStage<U> handle (BiFunction<? super T, Throwable, ? extends U> fn);
- 处理结果或异常
- fn 的两个入参是自身执行的结果和异常
- 抛出异常时,fn 的异常入参有值,否则为 null
- whenComplete
- 同上
- exceptionally
- 从异常计算一个结果
- exceptionallyCompose
- 对异常调用函数并执行返回的 future
组合多个 Future
- thenCombine
<U,V> CompletionStage<V> thenCombine (CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn);
- 执行两个动作并用给定函数组合结果
- 将自身和入参中的两个
CompletionStage
分别执行,两个结果传入fn
执行 - 有返回值
- thenAcceptBoth
<U> CompletionStage<Void> thenAcceptBoth (CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action);
- 同
thenCombine
- 无返回值
- runAfterBoth
CompletionStage<Void> runAfterBoth(CompletionStage<?> other, Runnable action);
- 两个动作都完成后执行
Runnable
- applyToEither
<U> CompletionStage<U> applyToEither (CompletionStage<? extends T> other, Function<? super T, U> fn);
- 得到其中一个动作的结果时,传入给定的函数
- acceptEither
CompletionStage<Void> acceptEither (CompletionStage<? extends T> other, Consumer<? super T> action);
- 同
applyToEither
- runAfterEither
CompletionStage<Void> runAfterEither(CompletionStage<?> other, Runnable action);
其他
toCompletableFuture
- 转为
CompletableFuture
- 转为
- CompletionStage concurrent 20230618 java utilcompletionstage concurrent 20230618 java completablefuture concurrent 20230618 java 20230618 stream java util concurrent java util rejectedexecutionexception concurrent java util basestream 20230618 stream java executorservice concurrent 20230713 java java线程concurrent工具 threadpoolexecutor concurrent 20230713 java concurrent 20230607 locks java