美文网首页
Java并发编程(九) CompletableFuture

Java并发编程(九) CompletableFuture

作者: skyguard | 来源:发表于2018-11-16 16:13 被阅读0次

    下面我们来分析一下java并发编程里的一个工具类CompletableFuture。我们知道,Future机制是java中的一种异步获取返回结果的方式,在jdk1.8中,提供了CompletableFuture这个类,能够更好的操作Future,和处理返回的结果。
    我们来看一下几个方法。先来看一下supplyAsync方法

    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }
    

    到asyncSupplyStage方法

    static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
                                                     Supplier<U> f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture<U> d = new CompletableFuture<U>();
        e.execute(new AsyncSupply<U>(d, f));
        return d;
    }
    

    调用execute方法执行任务
    再来看一下runAsync方法

    public static CompletableFuture<Void> runAsync(Runnable runnable,
                                                   Executor executor) {
        return asyncRunStage(screenExecutor(executor), runnable);
    }
    

    到asyncRunStage方法

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

    也是调用execute方法执行
    anyOf:判断多个CompletableFuture的执行结果,其中任意一个执行完返回执行结果
    allOf:多个CompletableFuture都执行完返回执行结果
    thenCompose:同时执行2个异步操作,将第一个CompletableFuture的返回值传递给第二个作为参数
    thenCombine:结合2个CompletableFuture的执行结果,通过一个BiFunction将2个Completable的返回值结合
    thenApply:对返回结果进行处理
    thenAccept:消费返回的结果,无返回值
    completeExceptionally:异常发生时的处理
    whenComplete:任务执行完,对返回的结果进行处理
    CompletableFuture的方法很多,可以对多个异步任务的返回结果进行组合,处理。
    CompletableFuture的分析就到这里了。

    相关文章

      网友评论

          本文标题:Java并发编程(九) CompletableFuture

          本文链接:https://www.haomeiwen.com/subject/bvumfqtx.html