CompletableFuture学习

简介: 前面我们已经知道CompletionService是可以解决Future带来的阻塞问题的,同时我们除了前面我们看到的take方法之外,还可以使用poll方法,这样可以使你的程序免受阻塞之苦。因为poll方法也是无阻塞性的。同时在kafka的源码中,我们如果使用消费者的话,可以看到会使用一个基于future的poll方法。同时我们可以在dubbo的新版本2.7中,可以看到其异步编程采用的就是我们要介绍的CompletableFuture。因此,我们有必要了解CompletableFuture,同时其也是真正意义上的异步编程的实现。

前面我们已经知道CompletionService是可以解决Future带来的阻塞问题的,同时我们除了前面我们看到的take方法之外,还可以使用poll方法,这样可以使你的程序免受阻塞之苦。因为poll方法也是无阻塞性的。同时在kafka的源码中,我们如果使用消费者的话,可以看到会使用一个基于future的poll方法。同时我们可以在dubbo的新版本2.7中,可以看到其异步编程采用的就是我们要介绍的CompletableFuture。因此,我们有必要了解CompletableFuture,同时其也是真正意义上的异步编程的实现。

packagecom.study.concurrent.completableFuture;
importjava.util.Random;
importjava.util.concurrent.CompletableFuture;
importjava.util.concurrent.*;
importjava.util.function.*;
/**** @description: CompletableFuture使用* <p>*  此demo的素材来源于https://www.jianshu.com/p/6bac52527ca4*  如果需要学习,请参考原文*  我将其加工成lambda表达式进行展示* </p>* @author: lyz* @date: 2020/05/30 17:48**/publicclassCompletableFutureTest {
publicstaticvoidmain(String[] args) throwsException {
//runAsync();//supplyAsync();// whenComplete();// theApply();// handle();// thenAccept();// thenCombine();// thenAcceptBoth();//  applyToEither();// acceptEither();// runAfterEither();//runAfterBoth()thenCompose();
    }
/**=====1、 runAsync 和 supplyAsync方法 ========**//*** 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)*///无返回值publicstaticvoidrunAsync() throwsException{
CompletableFuture<Void>future=CompletableFuture.runAsync(()->{
try{
TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedExceptione){
System.out.println("运行结束。。。");
            }
        });
future.get();
    }
publicstaticvoidsupplyAsync() throwsExecutionException, InterruptedException {
CompletableFuture<Long>future=CompletableFuture.supplyAsync(()->{
try{
TimeUnit.SECONDS.sleep(1);
            }catch (Exceptione){
            }
System.out.println("运行结束,你可以看到运行时间。。。");
returnSystem.currentTimeMillis();
        });
longtime=future.get();
System.out.println("time="+time);
    }
/**===============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)*///当CompletableFuture的计算结果完成,或者抛出异常,可以执行特定的Action//whenComplete 和 whenCompleteAsync 的区别://whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。//whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。publicstaticvoidwhenComplete() throwsInterruptedException {
CompletableFuture<Void>future=CompletableFuture.runAsync(()->{
try{
TimeUnit.SECONDS.sleep(2);
           } catch (InterruptedExceptione) {
e.printStackTrace();
           }
if(newRandom().nextInt()%2>=0){
inti=12/0;
           }
System.out.println("运行结束。。。");
        });
/* future.whenComplete(new BiConsumer<Void, Throwable>() {@Overridepublic void accept(Void aVoid, Throwable throwable) {System.out.println("执行完成");}});*/future.whenComplete((VoidaVoid, Throwablethrowable)->{
System.out.println("执行完成");
        });
/*future.exceptionally(new Function<Throwable, Void>() {@Overridepublic Void apply(Throwable throwable) {System.out.println("执行失败!"+throwable.getMessage());return null;}});*/future.exceptionally((Throwablethrowable)->{
System.out.println("执行失败!"+throwable.getMessage());
returnnull;
        });
TimeUnit.SECONDS.sleep(2);
    }
//3.theAppliy方法:当一个线程依赖另一个线程时,可以使用 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)*/publicstaticvoidtheApply() throwsExecutionException, InterruptedException {
/*CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>(){@Overridepublic Long get() {//执行任务一的业务long  result = new Random().nextInt(100);System.out.println("result="+result);return result;}}).thenApply(new Function<Long, Long>() {@Overridepublic Long apply(Long aLong) {//任务二的业务逻辑long result = aLong*5;return result;}});*/CompletableFuture<Long>future=CompletableFuture.supplyAsync(()->{
//执行任务一的业务longresult=newRandom().nextInt(100);
System.out.println("result="+result);
returnresult;
        }).thenApply((LongaLong)->{
//任务二的业务逻辑longresult=aLong*5;
returnresult;
        });
longresult=future.get();
System.out.println(result);
    }
/**======4.handle方法: handle是执行任务完成时对结果的处理========**///handle方法和thenApply方法处理方式基本一样,不同的是handle是在任务完成后再执行//还可以处理异常的任务。theApply只可以执行正常任务,任务出现异常则不会执行theApply方法/*** 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);*/publicstaticvoidhandle() throwsExecutionException, InterruptedException {
/* CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int i= 10/0;return 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());}return result;}});*/CompletableFuture<Integer>future=CompletableFuture.supplyAsync(()->{
inti=10/0;
returnnewRandom().nextInt(10);
        }).handle((Integerparam, Throwablethrowable)->{
intresult=-1;
if(throwable==null){
result=param*2;
                }else{
System.out.println(throwable.getMessage());
                }
returnresult;
        });
System.out.println(future.get());
    }
/**===========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);*///该方法只是消费执行完成的任务,并可以根据上面的任务返回的结果进行处理。并没有后续的输错操作publicstaticvoidthenAccept() throwsException{
/* CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {return new Random().nextInt(10);}}).thenAccept(integer -> {System.out.println(integer);});*/CompletableFuture<Void>future=CompletableFuture.supplyAsync(()->newRandom().nextInt(10)).thenAccept(System.out::println);
future.get();
    }
/**=========6.run方法:跟thenAccept方法不一样的是,不关心任务的处理结果。只要上面的任务执行完成,就开始执行 thenAccept====**//*** public CompletionStage<Void> thenRun(Runnable action);* public CompletionStage<Void> thenRunAsync(Runnable action);* public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);*///不同的是上个任务处理完成后,并不会把计算的结果传给 thenRun 方法。只是处理玩任务后,执行 thenAccept 的后续操作publicstaticvoidthenRun() throwsException{
/* CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {return new Random().nextInt(10);}}).thenRun(() -> {System.out.println("thenRun ...");});*/CompletableFuture<Void>future=CompletableFuture.supplyAsync(()->newRandom().nextInt(10)).thenRun(() ->System.out.println("thenRun ..."));
future.get();
    }
/**====7.thenCombine 合并任务:thetionCombine 会把 两个 ComplenStage 的任务都执行完成后,把两个任务的结果一块交给 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);*///这个就有点forkJoin的味道了privatestaticvoidthenCombine() throwsException {
/*      CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {return "hello";}});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {return "hello";}});CompletableFuture<String> result = future1.thenCombine(future2, new BiFunction<String, String, String>() {@Overridepublic String apply(String t, String u) {return t+" "+u;}});*/CompletableFuture<String>future1=CompletableFuture.supplyAsync(()->"hello");
CompletableFuture<String>future2=CompletableFuture.supplyAsync(()->"hello");
CompletableFuture<String>result=future1.thenCombine(future2, (t, u)->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);*///privatestaticvoidthenAcceptBoth() throwsException {
/* 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);return 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);return t;}});f1.thenAcceptBoth(f2, new BiConsumer<Integer, Integer>() {@Overridepublic void accept(Integer t, Integer u) {System.out.println("f1="+t+";f2="+u+";");}});*/CompletableFuture<Integer>f1=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f1="+t);
returnt;
        });
CompletableFuture<Integer>f2=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f2="+t);
returnt;
        });
f1.thenAcceptBoth(f2, (t, 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);**/privatestaticvoidapplyToEither() throwsException {
/* 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);return 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);return t;}});CompletableFuture<Integer> result = f1.applyToEither(f2, new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer t) {System.out.println(t);return t * 2;}});*/CompletableFuture<Integer>f1=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(4);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f1="+t);
returnt;
        });
CompletableFuture<Integer>f2=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(4);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f2="+t);
returnt;
        });
CompletableFuture<Integer>result=f1.applyToEither(f2, (Integert)->{
System.out.println(t);
returnt*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);*/privatestaticvoidacceptEither() throwsException {
/*  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);return 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);return t;}});f1.acceptEither(f2, new Consumer<Integer>() {@Overridepublic void accept(Integer t) {System.out.println(t);}});*/CompletableFuture<Integer>f1=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(5);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f1="+t);
returnt;
        });
CompletableFuture<Integer>f2=CompletableFuture.supplyAsync(()-> {
intt=newRandom().nextInt(5);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f2="+t);
returnt;
        });
// f1.acceptEither(f2, t-> System.out.println(t));f1.acceptEither(f2, System.out::println);
    }
/**===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);*/privatestaticvoidrunAfterEither() throwsException {
CompletableFuture<Integer>f1=CompletableFuture.supplyAsync(newSupplier<Integer>() {
@OverridepublicIntegerget() {
intt=newRandom().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f1="+t);
returnt;
            }
        });
CompletableFuture<Integer>f2=CompletableFuture.supplyAsync(newSupplier<Integer>() {
@OverridepublicIntegerget() {
intt=newRandom().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f2="+t);
returnt;
            }
        });
f1.runAfterEither(f2, newRunnable() {
@Overridepublicvoidrun() {
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);*/privatestaticvoidrunAfterBoth() throwsException {
/*  CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(6);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);return t;}});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(6);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);return t;}});f1.runAfterBoth(f2, new Runnable() {@Overridepublic void run() {System.out.println("上面两个任务都执行完成了。");}});*/CompletableFuture<Integer>f1=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(6);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f1="+t);
returnt;
        });
CompletableFuture<Integer>f2=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(6);
try {
TimeUnit.SECONDS.sleep(t);
                } catch (InterruptedExceptione) {
e.printStackTrace();
                }
System.out.println("f2="+t);
returnt;
        });
f1.runAfterBoth(f2, ()->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) ;*/privatestaticvoidthenCompose() throwsException {
/*CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = new Random().nextInt(3);System.out.println("t1="+t);return t;}}).thenCompose(new Function<Integer, CompletionStage<Integer>>() {@Overridepublic CompletionStage<Integer> apply(Integer param) {return CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int t = param *2;System.out.println("t2="+t);return t;}});}});*/CompletableFuture<Integer>f=CompletableFuture.supplyAsync(()->{
intt=newRandom().nextInt(7);
System.out.println("t1="+t);
returnt;
        }).thenCompose((Integerparam)->CompletableFuture.supplyAsync(()->{
intt=param*2;
System.out.println("t2="+t);
returnt;
                }));
System.out.println("thenCompose result : "+f.get());
    }
}


目录
相关文章
|
6月前
|
监控 Java API
并发编程 - CompletableFuture
并发编程 - CompletableFuture
48 0
|
15天前
|
Java API
java多线程之FutureTask、Future、CompletableFuture
java多线程之FutureTask、Future、CompletableFuture
|
2月前
|
前端开发 Java API
Java并发基础:CompletableFuture全面解析
CompletableFuture类使得并发任务的处理变得简单而高效,通过简洁的API,开发者能轻松创建、组合和链式调用异步操作,无需关心底层线程管理,这不仅提升了程序的响应速度,还优化了资源利用率,让复杂的并发逻辑变得易于掌控。
Java并发基础:CompletableFuture全面解析
|
5月前
CompletableFuture
CompletableFuture
23 0
|
6月前
|
Java 数据处理 数据库
CompletableFuture 使用
CompletableFuture 使用
34 0
|
7月前
|
Java 调度
并发编程——Future & CompletableFuture
Java创建线程的方式,一般常用的是Thread,Runnable。如果需要当前处理的任务有返回结果的话,需要使用Callable。Callable运行需要配合Future。
25 0
|
7月前
|
消息中间件 Java 中间件
Future and CompletableFuture
Future代表异步执行的结果,也就是说异步执行完毕后,结果保存在Future里, 我们在使用线程池submit()时需要传入Callable接口,线程池的返回值为一个Future,而Future则保存了执行的结果 ,可通过Future的get()方法取出结果,如果线程池使用的是execute(),则传入的是Runnable接口 无返回值。
36 0
|
8月前
|
Java
CompletableFuture总结和实践
CompletableFuture被设计在Java中进行异步编程。异步编程意味着在主线程之外创建一个独立的线程,与主线程分隔开,并在上面运行一个非阻塞的任务,然后通知主线程进展,成功或者失败。
225 0
|
9月前
|
Java
Java并发编程:深入理解CompletableFuture
一、引言 在Java的世界中,多线程编程一直被誉为其独特优势之一,而在Java 8中引入的CompletableFuture则为这一领域提供了更加强大和灵活的工具。本文将对CompletableFuture进行深度剖析,带你领略其在多线程开发中的实力。
65 0
Zp
【CompletableFuture】CompletableFuture中join()和get()方法的区别
【CompletableFuture】CompletableFuture中join()和get()方法的区别
Zp
505 0