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().get

本文介绍使用 Java 中的 CompletableFuture 进行异步处理的方法。通过对比同步与异步调用,展示如何利用 CompletableFuture 实现商品价格计算与其它任务的同时进行,显著减少总体执行时间。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



