JDK8-11-CompletableFuture(2)- CompletableFuture基本用法

CompletableFuture(2)- CompletableFuture基本用法

先看下如下例子:

Shop :店铺

getPrice :店铺中获取商品价格的方法

calculatePrice :店铺中具体计算价格的方法,sleep 1秒,模拟耗时

getPriceTest :同步调用测试方法,主线程首先调用 Shop getPrice 方法获取商品价格,然后再去做耗时 500 ms 的其他事情

public class Shop {

    private static final Random random = new Random();

    public double calculatePrice(String product) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return random.nextDouble() * product.charAt(0);
    }

    public double getPrice(String product) {
        System.out.println(Thread.currentThread() + " 开始计算商品价格...");
        return calculatePrice(product);
    }
    
    public static void getPriceTest(){
        long start = System.currentTimeMillis();
        System.out.println(new Shop().getPrice("apple"));
        System.out.println(Thread.currentThread()+" 开始做其他事情。。。");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("耗时:"+(System.currentTimeMillis()-start));
    }

   
    public static void main(String[] args) {
        getPriceTest();
    }
}

同步调用的测试结果如下,由于计算商品价格 1000 ms,做其他事情 500 ms,所以总的耗时 1500 ms 左右

Thread[main,5,main] 开始计算商品价格...
62.79737662147406
Thread[main,5,main] 开始做其他事情。。。
耗时:1512

以上是同步调用方式,但是计算商品价格和做其他事情两者没有关联关系,完全可以同时进行,通过 CompletableFuture 可以实现:

如下,主线程异步处理商品计算逻辑,不立即获取结果,然后再开始做其他事情(耗时500 ms),等这件事处理完后再获取商品结果,

public class Shop {

    private static final Random random = new Random();

    public double calculatePrice(String product) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return random.nextDouble() * product.charAt(0);
    }


    public Future<Double> getPriceAsync(String product) {
        //创建 CompletableFuture 对象,对象中包含异步计算结果
        CompletableFuture<Double> futurePrice = new CompletableFuture<>();
        //新建线程计算商品价格
        new Thread(() -> {
            double price = calculatePrice(product);
            //将异步计算得到的结果设置到 CompletableFuture 中,
            futurePrice.complete(price);
        }).start();
        //无需等待计算结果,直接返回 CompletableFuture 对象
        return futurePrice;
    }

    public static void getPriceAsyncTest(){
        long start = System.currentTimeMillis();
        Future<Double> priceFuture = new Shop().getPriceAsync("apple");
        System.out.println(Thread.currentThread()+" 开始做其他事情。。。");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            System.out.println(priceFuture.get());;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("耗时:"+(System.currentTimeMillis()-start));
    }

    public static void main(String[] args) {
        getPriceAsyncTest();
    }

}

如下,整个过程耗时 1148 ms,明显异步处理要比同步处理耗时要少

Thread[main,5,main] 开始做其他事情。。。
59.833564239289124
耗时:1148
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值