当前位置: 代码迷 >> 综合 >> java8 CompletableFuture异步编程
  详细解决方案

java8 CompletableFuture异步编程

热度:107   发布时间:2023-11-17 12:47:38.0

 1、创建异步对象

CompletableFuture提供了4个静态方法来创建一个异步操作:
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()作为它的线程执行异步代码。如果指定,则使用指定的线程池运行。源码:

  public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) {return asyncRunStage(screenExecutor(executor), runnable);}static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {if (f == null) throw new NullPointerException();CompletableFuture<Void> d = new CompletableFuture<Void>();e.execute(new AsyncRun(d, f));return d;}

ps:

runAsync()方法不支持返回值。

supplyAsync()可以执行返回值;

示例1:

CompletableFuture.runAsync(() -> {System.out.println("runAsync.....");}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);});}
runAsync.....
t:null
u:null

ps:这里的t是CompletableFuture.runAsync的返回值,u是CompletableFuture.runAsync返回的异常;由于CompletableFuture.runAsync没有返回值,所以这里的t是null。

示例2:

   CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync.....");//  int i = 1 / 0;return "hello,supplyAsync";}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);});String str = completableFuture.get();System.out.println("str:"+str);}
supplyAsync.....
t:hello,supplyAsync
u:null
str:hello,supplyAsync

ps:这里的t是CompletableFuture.supplyAsync()的返回值,u是CompletableFuture.supplyAsync()返回的异常;

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

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)

可以看到Action的类型是BiConsumer<? super T,? super Throwable>它可以处理正常的计算结果,或者异常情况。

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

方法不以Async结尾,意味着Action使用相同的线程执行,而Async可能会使用其他线程执行(如果是使用相同的线程池也可能会被同一个线程选中执行)

示例3:

 CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync.....");int i=1/0;return "hello,supplyAsync";}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);}).exceptionally(t->{System.out.println(t);return "hello,exceptionally";});
supplyAsync.....
t:null
u:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero

3、handle 方法:

handle 是执行任务完成时对结果的处理。
handle 实在任务完成后再执行,还可以处理异常任务。

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);

示例4:

    CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync.....");int i=1/0;return "hello,supplyAsync";}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);}).handleAsync((t,u)->{System.out.println("t:"+t);System.out.println("u:"+u);return "hello,handleAsync";});
supplyAsync.....
t:null
u:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
t:null
u:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero

4、线程串行化方法:

thenApply():当一个线程依赖另一个线程时,获取上一个任务返回的结果并返回当前任务的返回值。

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

thenRun():只要上面的任务执行完成就开始执行thenRun(),只要处理完任务后执行thenRun()的后续操作带有Async默认是异步执行的。这里的异步指的是不在当前线程内执行。

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)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 CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

示例5: 

  CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync.....");//   int i=1/0;return "hello,supplyAsync";}).thenApply(t->{System.out.println("t:"+t);return "hello,thenAccept";}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);}).handleAsync((t,u)->{System.out.println("t:"+t);System.out.println("u:"+u);return "hello,handleAsync";});
supplyAsync.....
t:hello,supplyAsync
t:hello,thenAccept
u:null
t:hello,thenAccept
u:null

示例6:

     CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync.....");//   int i=1/0;return "hello,supplyAsync";}).thenApply(t -> {System.out.println("t:" + t);return "hello,thenAccept1";}).thenApply(t -> {System.out.println("t:" + t);return "hello,thenAccept2";}).thenAccept(t -> {System.out.println("t:" + t);}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);}).handleAsync((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);return "hello,handleAsync";});
supplyAsync.....
t:hello,supplyAsync
t:hello,thenAccept1
t:hello,thenAccept2
t:null
u:null
t:null
u:null

5、两任务组合--都要完成

两个任务必须都要完成,触发该任务。

thenCombine():组合两个future,获取两个future的返回结果,并返回当前任务的返回值。

thenAcceptBoth():组合两个future获取两个future任务的返回结果,然后处理任务,没有返回值。

runAfterBoth():组合两个future,不需要获取future的结果,只需要两个future处理完成任务后,处理该任务。

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);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);

示例7:

       CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync.....");//   int i=1/0;return "hello,supplyAsync";}).thenApply(t -> {System.out.println("t:" + t);return "hello,thenAccept1";}).thenApply(t -> {System.out.println("t:" + t);return "hello,thenAccept2";}).thenAccept(t -> {System.out.println("t:" + t);}).whenComplete((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);}).handleAsync((t, u) -> {System.out.println("t:" + t);System.out.println("u:" + u);return "hello,handleAsync";}).thenCombine(CompletableFuture.completedFuture("hello,completedFuture"),(t,u)->{System.out.println("t:"+t);System.out.println("u:"+u);return "hello,thenCombine";});
supplyAsync.....
t:hello,supplyAsync
t:hello,thenAccept1
t:hello,thenAccept2
t:null
u:null
t:null
u:null
t:hello,handleAsync
u:hello,completedFuture

6、两任务组合--一个完成

当两个任务中,任意一个future任务完成的时候,执行任务。

applyToEither:两个任务有一个执行完成,获取它的返回值,处理任务并有新的返回值。

acceptEither:两个任务有一个执行完成,获取它的返回值,处理任务,没有新的返回值。

runAfterEither:两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值。

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);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);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);

7、多任务组合

allof:等待所有任务完成;

anyof:只要有一个任务完成;

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

示例8:

   CompletableFuture<String> c1 = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("supplyAsync1");return "supplyAsync1";});CompletableFuture<String> c2 = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("supplyAsync2");return "supplyAsync2";});long startTime = System.currentTimeMillis();CompletableFuture.allOf(c1,c2).join();long endTime = System.currentTimeMillis();System.out.println("耗时:"+(endTime-startTime)/1000);
supplyAsync2
supplyAsync1
耗时:3

 

  相关解决方案