CompletableFuture类方法详解
CompletableFuture类的方法详解
CompletableFuture
类是Java 8中新增的一个异步编程工具,它提供了一系列的方法来支持异步编程。下面对CompletableFuture
类的方法进行详解:
-
thenApply(Function<? super T, ? extends U> fn)
:将当前CompletableFuture
的计算结果作为参数传入fn
函数,并返回一个新的CompletableFuture
对象,该对象的计算结果为fn
函数的返回值。 -
thenAccept(Consumer<? super T> action)
:当当前CompletableFuture
计算完成后执行action
函数,不会返回新的CompletableFuture
对象。 -
thenRun(Runnable action)
:当当前CompletableFuture
计算完成后执行action
函数,不会接受任何参数和返回值。 -
thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
:将当前CompletableFuture
和other
的计算结果作为参数传入fn
函数,并返回一个新的CompletableFuture
对象,该对象的计算结果为fn
函数的返回值。 -
thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
:当当前CompletableFuture
和other
均计算完成后执行action
函数,不会返回新的CompletableFuture
对象。 -
runAfterBoth(CompletionStage<?> other, Runnable action)
:当当前CompletableFuture
和other
均计算完成后执行action
函数,不会接受任何参数和返回值。 -
applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)
:当当前CompletableFuture
或other
中任意一个计算完成时就将其计算结果作为参数传入fn
函数,并返回一个新的CompletableFuture
对象,该对象的计算结果为fn
函数的返回值。 -
acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
:当当前CompletableFuture
或other
中任意一个计算完成时就执行action
函数,不会返回新的CompletableFuture
对象。 -
runAfterEither(CompletionStage<?> other, Runnable action)
:当当前CompletableFuture
或other
中任意一个计算完成时就执行action
函数,不会接受任何参数和返回值。 -
exceptionally(Function<Throwable, ? extends T> fn)
:当当前CompletableFuture
出现异常时,将异常作为参数传入fn
函数,该函数可以处理异常并返回一个新的计算结果。 -
handle(BiFunction<? super T, Throwable, ? extends U> fn)
:当当前CompletableFuture
计算完成时,将计算结果和异常(如果有的话)作为参数传入fn
函数,并返回一个新的CompletableFuture
对象,该对象的计算结果为fn
函数的返回值。 -
whenComplete(BiConsumer<? super T, ? super Throwable> action)
:当当前CompletableFuture
计算完成时,将计算结果和异常(如果有的话)作为参数传入action
函数,不会返回新的CompletableFuture
对象。 -
allOf(CompletableFuture<?>... cfs)
:返回一个新的CompletableFuture
对象,当所有cfs
中的CompletableFuture
均计算完成时该对象的计算也完成。 -
anyOf(CompletableFuture<?>... cfs)
:返回一个新的CompletableFuture
对象,当cfs
中的任意一个CompletableFuture
计算完成时该对象的计算也完成。