public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn); public CompletionStage<Void> thenAccept(Consumer<? super T> action); public CompletionStage<Void> thenRun(Runnable action); public <U> CompletionStage<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
和另一个Stage都完成后进行后续处理
CompletionStage.java
1 2 3
public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn); public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action); public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
和另一Stage任一完成后进行后续处理
CompletionStage.java
1 2 3
public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn); public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action); public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
异常处理
CompletionStage.java
1 2 3
public CompletionStage<T> exceptionally(Function<Throwable, ? extends T> fn); public CompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action); public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public CompletableFuture<Void> thenAccept(Consumer<? super T> action){ return uniAcceptStage(null, action); } private CompletableFuture<Void> uniAcceptStage(Executor e, Consumer<? super T> f){ if (f == null) thrownew NullPointerException(); //生成一个新的CompletableFuture CompletableFuture<Void> d = new CompletableFuture<Void>(); //this当前对象表示上游,没有线程池时直接尝试当前线程执行uniAccept if (e != null || !d.uniAccept(this, f, null)) { //有线程池时,或者没有线程池但是上游还没完成,构建任务进栈 UniAccept<T> c = new UniAccept<T>(e, d, this, f); push(c); c.tryFire(SYNC); } return d; }
final <S> booleanuniAccept(CompletableFuture<S> a, Consumer<? super S> f, UniAccept<S> c){ Object r; Throwable x; //上游结果是null,说明上游没结束,直接返回false if (a == null || (r = a.result) == null || f == null) returnfalse; tryComplete: if (result == null) { if (r instanceof AltResult) { if ((x = ((AltResult)r).ex) != null) { completeThrowable(x, r); break tryComplete; } r = null; } try { if (c != null && !c.claim()) returnfalse; //执行当前 @SuppressWarnings("unchecked") S s = (S) r; f.accept(s); completeNull(); } catch (Throwable ex) { completeThrowable(ex); } } returntrue; }