3.3.2 applyToEither
applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)
当前调用的Stage或者参数中的other Stgae中任何一个正常完成,均执行给定的Function,并且使用之前相应的result作为输入值(当前调用的Stage结果优先级高于参数中的Stage),并返回CompletionStage。
3.3.3 thenCompose
只有一个Function参数,Function中的输入值T为当前Stage的结果,输出值为一个CompletionStage, 返回一个新的CompletionStage,
其余的方法同上。
3.3.4 thenCombine
这个方法是用到了 BiFunction
T,U为apply方法的第一个和第二个参数,R为返回值。
thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn)
这个方法和它的名称一样,就是合并两个Stage的结果。当前Stage的result,和参数中的other Stage的result作为参数中BiFunction的两个输入参数,最终返回一个新的CompletionStage。
3.3.5 handle
handle(BiFunction<? super T, Throwable, ? extends U> fn)
使用此Stage的Result作为一个参数,还有一个异常为参数,执行BiFunction,并将执行的结果作为返回的CompletableFuture的result。其与方法为异步执行方法。
3.4 主要参数为Consumer的方法
Consumer是一个只有输入参数,没有返回值的Lamada,其方法 void accept(T t), 即表示只有输入参数没有返回值。
3.4.1 thenAccept
thenAccept(Consumer<? super T> action)
看完了上面的几组方法,这个方法很容易就能明白,即当前Stage正常完成的情况下,将当前Stage的result作为参数,执行Consumer,并且返回一个没有resulet的CompletableFuture。
3.4.2 thenAccept
acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
同上面带有Either的方法差不多,即当前Stage 或者参数中的Other Stgae正常完成后执行Comsumer,并且将Stage的result作为Comsumer的输入值,(同上,调用放的Stage的result优先级更高!)
3.4.3 thenAcceptBoth
thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer <? super T, ? super U> action)
同上,即需要两个Stage都正常完成才会去执行 BiConsumer。由于BiConsumer有两个输入值,则Stage的result分别为BiConsumer计算的输入值,最后返回一个不包含Result的CompletableFuture。
3.4.4 whenComplete
whenComplete(BiConsumer<? super T, ? super Throwable> action)
顾名思义,就是当前调用的stage完成的时候执行参数中的方法,并且返回包含同一个结果的CompletableFuture,如果有异常也会返回指定的异常。
总结
本篇为妹子讲了一下CompletableFuture的内容特点。相信聪明的美女同事已经比较熟悉CompleteableFuture的应用了!下期我们再来讲解CompletableFuture的使用场景以及应用示例。
面试大全包括:包括 Java 集合、JVM、多线程、并发编程、设计模式、SpringBoot、SpringCloud、Java、MyBatis、ZooKeeper、Dubbo、Elasticsearch、Memcached、MongoDB、Redis、MySQL、RabbitMQ、Kafka、Linux、Netty、Tomcat、Python、HTML、CSS、Vue、React、JavaScript、Android 大数据、阿里巴巴等大厂面试题等、等技术栈!
领取方式:扫描下方公众号【Java技术指北】回复【006】即可获取