需求
实现
package com.cheng;
import lombok.Getter;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class CompletableFutureMall {
// 构造三家购物网站
static List<NetMall> list = Arrays.asList(
new NetMall("jd"),
new NetMall("taobao"),
new NetMall("dangdang")
);
/**
* 从每个网站依次获取商品价格
* ProductName:书名
*/
public static List<String> getPrice(List<NetMall> list, String productName){
return list
.stream()
.map(netMall ->
String.format("%s in %s price is %.2f",
productName,
netMall.getNetMallName(),
netMall.calcPrice(productName)))
.collect(Collectors.toList());
}
public static List<String> getPriceByCompletableFuture(List<NetMall> list, String productName){
return list.stream()
.map(netMall -> CompletableFuture.supplyAsync(()-> String.format("%s in %s price is %.2f",
productName,
netMall.getNetMallName(),
netMall.calcPrice(productName))))
.collect(Collectors.toList())
.stream()
.map(s -> s.join())
.collect(Collectors.toList());
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<String> prices = getPrice(list, "mysql");
for (String price : prices) {
System.out.println(price);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
start = System.currentTimeMillis();
prices = getPriceByCompletableFuture(list, "mysql");
for (String price : prices) {
System.out.println(price);
}
end = System.currentTimeMillis();
System.out.println(end - start);
}
}
// 模拟一个网站的价格
class NetMall{
@Getter
private final String netMallName;
public NetMall(String netMallName){
this.netMallName = netMallName;
}
public double calcPrice(String productName){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
}
}
结果
mysql in jd price is 109.43
mysql in taobao price is 109.93
mysql in dangdang price is 110.49
3122
mysql in jd price is 109.25
mysql in taobao price is 110.61
mysql in dangdang price is 109.05
1009
Process finished with exit code 0
结论
使用CompletableFuture大大提高了程序性能!!!