当前位置: 首页 >Java技术 > Java CompletableFuture 详解

Java CompletableFuture 详解

      Future是Java 5添加的类,用来描述一个异步计算的结果。你可以使用isDone方法检查计算是否完成,或者使用get阻塞住调用线程,直到计算完成返回结果,你也可以使用cancel方法停止任务的执行。

public class BasicFuture {public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService es = Executors.newFixedThreadPool(10);Future<Integer> f = es.submit(() ->{// 长时间的异步计算// ……// 然后返回结果retu 100;});//while(!f.isDone())//;f.get();}}

      虽然Future以及相关使用方法提供了异步执行任务的能力,但是对于结果的获取却是很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然和我们的异步编程的初衷相违背,轮询的方式又会耗费无谓的CPU资源,而且也不能及时地得到计算结果。为什么不能用观察者设计模式当计算结果完成及时通知监听者呢?

      在Java 8中, 新增加了一个包含50个方法左右的类: CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。CompletableFuture类实现了CompletionStageFuture接口,所以你还是可以像以前一样通过阻塞或者轮询的方式获得结果,尽管这种方式不推荐使用。

       1、 runAsync 和 supplyAsync方法

             CompletableFuture 提供了四个静态方法来创建一个异步操作。

public static CompletableFuture<Void> runAsync(Runnable runnable)public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

         没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同。

        runAsync方法不支持返回值。它是以Runnable函数式接口类型为参数,所以CompletableFuture的计算结果为空。

        supplyAsync可以支持返回值。它是以Supplier<U>函数式接口类型为参数,CompletableFuture的计算结果类型为U

    示例     

//无返回值public static void runAsync() throws Exception {CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}System.out.println("run end ...");});future.get();}//有返回值public static void supplyAsync() throws Exception { CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}System.out.println("run end ...");retu System.currentTimeMillis();});long time = future.get();System.out.println("time = "+time);}

2 、计算完成时的回调方法

      当CompleteableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的action。主要是下面的方法:

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

whenComplete 和 whenCompleteAsync 的区别:
    whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。
    whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。

示例

public static void whenComplete() throws Exception {CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}if(new Random().nextInt()%2>=0) {int i = 12/0;}System.out.println("run end ...");});future.whenComplete(new BiConsumer<Void, Throwable>() {@Overridepublic void accept(Void t, Throwable action) {System.out.println("执行完成!");}});future.exceptionally(new Function<Throwable, Void>() {@Overridepublic Void apply(Throwable t) {System.out.println("执行失败!"+t.getMessage());retu null;}});TimeUnit.SECONDS.sleep(2);}

3、 thenApply 方法

      当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化。      

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)

Function<? super T,? extends U>
    T:上一个任务返回结果的类型
    U:当前任务的返回值类型

示例

private static void thenApply() throws Exception {CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {@Overridepublic Long get() {long result = new Random().nextInt(100);System.out.println("result1="+result);retu result;}}).thenApply(new Function<Long, Long>() {@Overridepublic Long apply(Long t) {long result = t*5;System.out.println("result2="+result);retu result;}});long result = future.get();System.out.println(result);}

第二个任务依赖第一个任务的结果。

4、 handle 方法

    handle 是执行任务完成时对结果的处理。
    handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。

public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);

示例

public static void handle() throws Exception{CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int i= 10/0;retu new Random().nextInt(10);}}).handle(new BiFunction<Integer, Throwable, Integer>() {@Overridepublic Integer apply(Integer param, Throwable throwable) {int result = -1;if(throwable==null){result = param * 2;}else{System.out.println(throwable.getMessage());}retu result;} });System.out.println(future.get());}

      从示例中可以看出,在 handle 中可以根据任务是否有异常来进行做相应的后续处理操作。而 thenApply 方法,如果上个任务出现错误,则不会执行 thenApply 方法。

5、 thenAccept 消费处理结果

      接收任务的处理结果,并消费处理,无返回结果。

public CompletionStage<Void> thenAccept(Consumer<? super T> action);public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

示例

public static void thenAccept() throws Exception{CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {retu new Random().nextInt(10);}}).thenAccept(integer -> {System.out.println(integer);});future.get();}

从示例代码中可以看出,该方法只是消费执行完成的任务,并可以根据上面的任务返回的结果进行处理。并没有后续的输出操作。

6、thenRun 方法

      跟 thenAccept 方法不一样的是,不关心任务的处理结果。只要上面的任务执行完成,就开始执行 thenAccept 。      

public CompletionStage<Void> thenRun(Runnable action);public CompletionStage<Void> thenRunAsync(Runnable action);public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

示例

public static void thenRun() throws Exception{CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {retu new Random().nextInt(10);}}).thenRun(() -> {System.out.println("thenRun ...");});future.get();}

       该方法同 thenAccept 方法类似。不同的是上个任务处理完成后,并不会把计算的结果传给 thenRun 方法。只是处理完任务后,执行 thenAccept 的后续操作。

7、thenCombine 合并任务

        thenCombine 会把 两个 CompletionStage 的任务都执行完成后,把两个任务的结果一块交给 thenCombine 来处理。

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);

示例

private static void thenCombine() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {retu "hello";}});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {retu "hello";}});CompletableFuture<String> result = future1.thenCombine(future2, new BiFunction<String, String, String>() {@Overridepublic String apply(String t, String u) {retu t+" "+u;}});System.out.println(result.get());}

8、thenAcceptBoth

当两个CompletionStage都执行完成后,把结果一块交给thenAcceptBoth来进行消耗

public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor);

示例

private static void thenAcceptBoth() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);retu t;}});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);retu t;}});f1.thenAcceptBoth(f2, new BiConsumer<Integer, Integer>() {@Overridepublic void accept(Integer t, Integer u) {System.out.println("f1="+t+";f2="+u+";");}});}

9、applyToEither 方法

        两个CompletionStage,谁执行返回的结果快,我就用那个CompletionStage的结果进行下一步的转化操作。

public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);

示例

private static void applyToEither() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);retu t;}});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);retu t;}});CompletableFuture<Integer> result = f1.applyToEither(f2, new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer t) {System.out.println(t);retu t * 2;}});System.out.println(result.get());}

10、acceptEither 方法

       两个CompletionStage,谁执行返回的结果快,我就用那个CompletionStage的结果进行下一步的消耗操作。

public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);

示例

private static void acceptEither() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);retu t;}});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);retu t;}});f1.acceptEither(f2, new Consumer<Integer>() {@Overridepublic void accept(Integer t) {System.out.println(t);}});}

11、runAfterEither 方法

两个CompletionStage,任何一个完成了都会执行下一步的操作(Runnable)

public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);

示例

private static void runAfterEither() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);retu t;}});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);retu t;}});f1.runAfterEither(f2, new Runnable() {@Overridepublic void run() {System.out.println("上面有一个已经完成了。");}});}

12、runAfterBoth

两个CompletionStage,都完成了计算才会执行下一步的操作(Runnable)

public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);

示例

private static void runAfterBoth() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);retu t;}});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);retu t;}});f1.runAfterBoth(f2, new Runnable() {@Overridepublic void run() {System.out.println("上面两个任务都执行完成了。");}});}

13、thenCompose 方法

thenCompose 方法允许你对两个 CompletionStage 进行流水线操作,第一个操作完成时,将其结果作为参数传递给第二个操作。

public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) ;public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn, Executor executor) ;

示例

private static void thenCompose() throws Exception {CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);System.out.println("t1="+t);retu t;}}).thenCompose(new Function<Integer, CompletionStage<Integer>>() {@Overridepublic CompletionStage<Integer> apply(Integer param) {retu CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = param *2;System.out.println("t2="+t);retu t;}});}});System.out.println("thenCompose result : "+f.get());}

辅助方法 allOf 和 anyOf

        前面我们已经介绍了几个静态方法:completedFuturerunAsyncsupplyAsync,下面介绍的这两个方法用来组合多个CompletableFuture。

public static CompletableFuture<Void> 	allOf(CompletableFuture<?>... cfs)public static CompletableFuture<Object> 	anyOf(CompletableFuture<?>... cfs)

allOf方法是当所有的CompletableFuture都执行完后执行计算。

anyOf方法是当任意一个CompletableFuture执行完后就会执行计算,计算的结果相同。

      下面的代码运行结果有时是100,有时是"abc"。但是anyOfapplyToEither不同。anyOf接受任意多的CompletableFuture但是applyToEither只是判断两个CompletableFuture,anyOf返回值的计算结果是参数中其中一个CompletableFuture的计算结果,applyToEither返回值的计算结果却是要经过fn处理的。当然还有静态方法的区别,线程池的选择等。

Random rand = new Random();CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(10000 + rand.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}retu 100;});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(10000 + rand.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}retu "abc";});//CompletableFuture<Void> f =  CompletableFuture.allOf(future1,future2);CompletableFuture<Object> f =  CompletableFuture.anyOf(future1,future2);System.out.println(f.get());

 

作者:老木木
来源链接:https://www.cnblogs.com/laomumu/p/12386971.html

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaclub.cn/java/117267.html

分享给朋友:

“Java CompletableFuture 详解” 的相关文章