前提:
本章中的演示是在8核cpu上进行的,你需要根据你的cpu的核数增减商店的数量,才能看到相同的效果
Shop.java
public class Shop {
//省略掉一些代码,只看关键部分
public static void delay() { // 1
try {
Thread.sleep(1000L);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private double calculatePrice(String product) { // 2
delay();
return random.nextDouble() * 100;
}
public Future<Double> getPriceAsync(String product) {
CompletableFuture<Double> futurePrice = new CompletableFuture<>(); // 3
new Thread(() -> futurePrice.complete(calculatePrice(product))).start(); // 4
return futurePrice; // 5
}
public static void main(String[] args) throws Exception {
Shop shop = new Shop("BestShop");
long start = System.currentTimeMillis();
Future<Double> futurePrice = shop.getPriceAsync("some product"); // 6
System.out.println("调用返回,耗时:"+ (Sy