CompletableFuture的一例使用

CompletableFuture提供了丰富的api,底层实现是ForkJoinPool。可以用来一个任务拆分成多个任务,最后将结果集汇总输出。

比如说在网约车计费的情况下,其计算规则有很多种,按路程算钱,按时间算钱,路程又根据距离的远近计价不同,时间有可能根据时间点的不同以及等待的时间等规则计价,最后将各规则的价格汇总到一起形成个总价。

模拟计价代码:

public class MainTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        Long sum = getPrice1() + getPrice2() + getPrice3();
        long end = System.currentTimeMillis();
        System.out.println(sum+ "  " +(end - start));
        start = System.currentTimeMillis();
        CompletableFuture<Long> cf1 = CompletableFuture.supplyAsync(()->getPrice1());
        CompletableFuture<Long> cf2 = CompletableFuture.supplyAsync(()->getPrice2());
        CompletableFuture<Long> cf3 = CompletableFuture.supplyAsync(()->getPrice3());
        MyFunction myFunction = new MyFunction();
        CompletableFuture<Long> longCompletableFuture = cf1.thenCombineAsync(cf2, myFunction)
                .thenCombineAsync(cf3, myFunction);
        Long aLong = longCompletableFuture.get();
        end = System.currentTimeMillis();
        System.out.println(aLong+"  "+ (end - start));
    }

    /**
     * 自定义函数 计算两个数之和
     */
    private static class MyFunction implements BiFunction<Long, Long, Long>{
        @Override
        public Long apply(Long aLong, Long aLong2) {
            return aLong+aLong2;
        }
    }

    //规则一计价
    public static long getPrice1(){
        delay();
        return 28;
    }

    //规则二计价
    public static long getPrice2(){
        delay();
        return 33;
    }
    //规则三计价
    public static long getPrice3(){
        delay();
        return 35;
    }

    //模拟计算延时,为了方便统一延时2秒
    private static void delay() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值