它们与thenApply* 办法的差别在于handle*办法会处理正常计算值和异常,是以它可以樊篱异常,避免异常持续抛出。而thenApply*办法只是用来处理正常值,是以一旦有异常就会抛出。
纯花费结不雅
膳绫擎的办法是当计算完成的时刻,会生成新的计算结不雅(thenApply, handle),或者返回同样的计算结不雅(whenComplete,CompletableFuture)。CompletableFuture供给了一种处理结不雅的办法,只短卺不雅履行Action,而不返回新的计算值,是以计算值为Void:
看它的参数类型也就明白了,它们是花费型函数式接口Consumer,这个接口只有输入,没有返回值。
- CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
- return 100;
- });
- CompletableFuture<Void> f = future.thenAccept(System.out::println);
- System.out.println(f.get());
- public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
- public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
- public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor)
- public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
thenAcceptBoth以及相干办法供给了类似的功能,当两个CompletionStage都正常完成计算的时刻,就会履行供给的action,它用来组合别的一个异步的结不雅。
runAfterBoth是当两个CompletionStage都正常完成计算的时刻,履行一个Runnable,这个Runnable并不应用计算的结不雅。
更彻底地,下面一组办法当计算完成的时刻会履行一个Runnable,与thenAccept不合,Runnable并不应用CompletableFuture计算的结不雅。
- public CompletableFuture<Void> thenRun(Runnable action)
- public CompletableFuture<Void> thenRunAsync(Runnable action)
- public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
是以先前的CompletableFuture计算的结不雅被忽视了,这个办法返回CompletableFuture<Void>类型的对象。
是以,你可以根据办法的参数的类型来加快你的记忆。Runnable类型的参数会忽视计算的结不雅,Consumer是纯花费计算结不雅,BiConsumer会组合别的一个CompletionStage纯花费,Function会对计算结不雅做转换,BiFunction会组合别的一个CompletionStage的计算结不雅做转换。
组合
有时,你须要在一个future构造运行某个函数,然则这个函数也是返回某种future,也就是说是两个future彼此依附串联在一路,它类似于flatMap。

网友点评
精彩导读
科技快报
品牌展示