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