CompletableFuture 大展身手(二)

一、Completable常用方法(二)

  1. 收尾处理
    1.1 whenComplete方法
    当一个任务处理结束后,可以对得到的数据进行处理。
返回值 方法名 介绍
CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) 当任务完成时采取的处理并且可以对异常处理,使用ForkJoinPool线程池
CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) 当任务完成时采取的处理并且可以对异常处理,使用ForkJoinPool线程池
CompletableFuture<T> twhenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor) 当任务完成时采取的处理并且可以对异常处理,自定义线程池
   CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "hello";
        }).thenApply((w)->w+"world"+(1/0))
          .whenCompleteAsync((w,throwable)->{
            System.out.println(throwable.getMessage());
        });

在代码中有个ArithmeticException,在whenComplete时进行了处理。
2.2 handle方法
handle方法与whenComplete方法类似,不同的是handle方法中传入了一个BiFunction,意味着handle方法可以拥有返回值;

返回值 方法名 介绍
CompletableFuture<U> handle( BiFunction<? super T, Throwable, ? extends U> fn) 当任务完成时采取的处理并且对异常可以处理,使用ForkJoinPool线程池
CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) 当任务完成时采取的处理并且对异常可以处理,使用ForkJoinPool线程池
CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) 当任务完成时采取的处理并且对异常可以处理,自定义线程池
CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "hello";
        }).thenApply((w)->w+"world"+(1/0))
          .handleAsync((w,throwable)->{
              System.out.println(throwable.getMessage());
              return "好嗨哦";
        });
        future.get();

1.3 thenAccept方法
thenAccept方法没有返回值,并且不能对异常进行处理。

返回值 方法名 介绍
CompletableFuture<Void> thenAccept(Consumer<? super T> action) 当任务完成时采取的处理,使用ForkJoinPool线程池
CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) 当任务完成时采取的处理,使用ForkJoinPool线程池
CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) 当任务完成时采取的处理,自定义线程池
CompletableFuture<Void> future = CompletableFuture.supplyAsync(()->{
            return "hello";
        }).thenApply((w)->w+"world")
          .thenAcceptAsync((w)->{
            System.out.println("真的有意思");
        });
        System.out.println(future.get());
  1. one of two
    one of two 就是两者中任意一个完成就发出通知;
    2.1 acceptEither方法
返回值 方法名 介绍
CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) 两个任务完成其中一个就开始执行action,使用ForkJoinPool线程池
CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action) 两个任务完成其中一个就开始执行action,使用ForkJoinPool线程池
CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) 两个任务完成其中一个就执行action,自定义线程池
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "HELLOW";
        }).thenApply((w)->w+"WORLD");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "hello";
        }).thenApply((w)->w+"world");
        
        
CompletableFuture<Void> future2 = 
                future.acceptEitherAsync(future1,(w)->System.out.println("我看看是哪个Hello world\n"+w));

2.2 applyToEither方法
applyToEither 和acceptEither方法类似,只是applyToEither方法可以返回结果,applyToEither方法传入了Function接口

返回值 方法名 介绍
CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn) 两个任务完成其中一个就开始执行action,使用ForkJoinPool线程池
CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn) 两个任务完成其中一个就开始执行action,使用ForkJoinPool线程池
CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn,
Executor executor) 两个任务完成其中一个就执行action,自定义线程池
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "HELLOW";
        }).thenApply((w)->w+"WORLD");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "hello";
        }).thenApply((w)->w+"world");
        
        
CompletableFuture<String> future2 = 
                future.applyToEither(future1,(w)->{return "我看看是哪个Hello world\n"+w;});
System.out.println(future2.get());

3 all of them
上面介绍了两个任务完成一个就会通知,下面介绍许多(大于两个)任务完成通知和许多任务完成才会通知。
3.1 allOf

返回值 方法名 介绍
CompletableFuture<Void> applyToEitherallOf(CompletableFuture<?>... cfs) 当所有任务完成时会执行此方法
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "HELLOW";
        }).thenApply((w)->w+"WORLD");
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(()->{
            return "真的";
        }).thenApply((w)->w+"有意思");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "头发";
        }).thenApply((w)->w+"快没了");
        
CompletableFuture
     .allOf(future1,future2,future)
     .thenApply(v->Stream.of(future1,future2,future)
     .map(t -> {
    try {
        return t.get();
         } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
         } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        return null;
       })
       .collect(Collectors.toList()))
    .thenAccept(System.out::println);

3.2 anyOf

返回值 方法名 介绍
CompletableFuture<Void> anyOf(CompletableFuture<?>... cfs) 当其中一个任务完成时会执行此方法
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "HELLOW";
        }).thenApply((w)->w+"WORLD");
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(()->{
            return "真的";
        }).thenApply((w)->w+"有意思");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "头发";
        }).thenApply((w)->w+"快没了");
        
        CompletableFuture<Object> future3 = CompletableFuture
                .anyOf(future1,future2,future);
        System.out.println(future3.get());
  1. 异常
    当执行过程中出现异常,可以对异常进行处理,当然使用get也可以抛出异常。
返回值 方法名 介绍
CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn) 当异步任务执行抛出异常时会执行此方法
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "HELLOW"+1/0;
        }).thenApply((w)->w+"WORLD").exceptionally((throwable)->{
            System.out.println(throwable);
            return null;
        });
System.out.println(future1.get());

以上就是CompletableFuture常用的方法,很多基于应用,深入底层的很少,希望对想快速入手的朋友有很大的帮助。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容