Java核心复习——CompletableFuture

介绍

JDK1.8引入CompletableFuture类。

使用方法


public class CompletableFutureTest {

    private static ExecutorService threadPool = new ThreadPoolExecutor(40, 100,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(20));

    public String B() {
        System.out.println("执行方法B");
        sleep(5);
        return "Function B";
    }

    public String C() {
        System.out.println("执行方法C");
        sleep(20);
        return "Function C";
    }


    public void sleep(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void testCompableFuture() {
        CompletableFuture<String> future;
        try {
            //Returns a new CompletableFuture 
            // that is asynchronously completed by a task running in the given executor 
            // with the value obtained by calling the given Supplier.
            future = CompletableFuture.supplyAsync(() -> B(), threadPool);
            //若去掉线程池,有何区别future = CompletableFuture.supplyAsync(() -> B());

            sleep(9);
            System.out.println(future.toString());
            System.out.println(future.isDone());
        } catch (RejectedExecutionException e) {
            System.out.println("调用搜索列表服务线程满负荷, param:{}");
        }
    }

    public static void main(String[] args) {
        CompletableFutureTest test = new CompletableFutureTest();
        test.testCompableFuture();
    }

}

API

supplyAsync方法

JDK方法描述

/**
     * Returns a new CompletableFuture that is asynchronously completed
     * by a task running in the given executor with the value obtained
     * by calling the given Supplier.
     *
     * @param supplier a function returning the value to be used
     * to complete the returned CompletableFuture
     * @param executor the executor to use for asynchronous execution
     * @param <U> the function's return type
     * @return the new CompletableFuture
     */
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }

应用场景

请求A的执行方法X,需满足下列需求:

①请求B、C、D中任一一个请求有返回结果,则X方法返回响应结果。

②请求B、C、D中都执行完,则X方法返回响应结果。

源码阅读

依赖关系

在这里插入图片描述

参考文档

JDK API文档
20 个使用 Java CompletableFuture的例子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值