CompletableFuture与CompletionStage使用

对Future的补充,Futrue的get()方法采用阻塞获取或者是轮询isDone()。
CompletionFuture的get()可做异步回调,类似AIO。

1.创建CompletionFuture

    /** 使用默认ForkJoinPool.commonPool(),异步完成,有返回值 */
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) { return asyncSupplyStage(asyncPool, supplier); }

    /** 使用给定的executor,异步完成,有返回值 */
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) { return asyncSupplyStage(screenExecutor(executor), supplier); }

    /** 使用默认ForkJoinPool.commonPool(),异步完成,无返回值 */
    public static CompletableFuture<Void> runAsync(Runnable runnable) { return asyncRunStage(asyncPool, runnable); }

    /** 使用给定的executor,异步完成,无返回值 */
    public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) { return asyncRunStage(screenExecutor(executor), runnable);  }

2.纯消费类型的方法,返回的是void

    /** 返回一个新的 CompletionStage,当此阶段正常完成时,将使用此阶段的结果作为提供的操作的参数来执行 */
    public CompletionStage<Void> thenAccept(Consumer<? super T> action);

    /**返回一个新的 CompletionStage,当这个阶段正常完成时,使用这个阶段的默认异步执行工具执行,这个阶段的结果作为提供的操作的参数*/
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);

    /** 返回一个新的 CompletionStage,当这个阶段正常完成时,使用提供的 Executor 执行,这个阶段的结果作为提供的操作的参数 */
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor);

3.有返回值的方法


4.不返回也不消费


5.组合类型


vans.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容