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