通用的使用方式
whenComplete 直接获取对应的返回结果。
如果计算正确代码执行 whenComplete,计算错误则走 exceptionally。 这与vue3.X前端获取接口的使用方式大致一样。
/**
* whenComplete(v,e)
* exceptionally(e)
* v 表示获取上一步线程计算的结果
* e 表示异常信息
*/
public class ComplatebleFutureDemo02 {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(3);
try {
CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName());
int result = ThreadLocalRandom.current().nextInt(10);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (result>5){
int i = 10/0;
}
System.out.println("输出结果:" + result);
return result;
//v 指的是 上一步的返回结果result, e表示异常
}, threadPool).whenComplete((v, e) -> {
if (e == null) {
System.out.println("没有异常");
System.out.println("计算结果:" + v);
}
}).exceptionally(e -> {
e.printStackTrace();
System.out.println(e.getCause()+e.getMessage());
return null;
});
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
System.out.println("主线程先去干其他的事情");
}
}
join 与 get 的区别:
作用基本一样,只是使用join没有异常检查,而get有异常检查且必须抛出异常。
电商比价需求分析:
假如在某东平台,需要比较多个入住商家卖《java编程思想》这本书,分别卖多少钱。希望的结果是输出,同一个产品在不同商家的价格清单。
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
List<String> mysql = getPrice(list, "mysql");
for (String element : mysql) {
System.out.println(element);
}
long endTime = System.currentTimeMillis();
System.out.println("------ costTime :" + (endTime - startTime) + "毫秒");
}
class NetMall {
private String netMallName;
public NetMall(String netMallName) {
this.netMallName = netMallName;
}
public String getNetMallName() {
return netMallName;
}
public double calcPrice(String productName) {
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
}
}
static List<NetMall> list = Arrays.asList(
new NetMall("JD"),
new NetMall("TB"),
new NetMall("pdd")
);
/**
* 使用CompletableFuture 启动多个异步线程同时去干,1101毫秒
* List<NetMall> ----映射----List<CompletableFuture> ----映射---- List<String>
*
* @param list
* @param productName
* @return
*/
public static List<String> getPrice(List<NetMall> list, String productName) {
return list
.stream()
//.map() 类似于映射,相当于把List<NetMall> list里面的数据全部映射到CompletableFuture.supplyAsync(()里面。
.map(netMall ->
CompletableFuture.supplyAsync(() ->
String.format(productName + " in %s price is %s.2f", netMall.getNetMallName(), netMall.calcPrice(productName))
))
.collect(Collectors.toList())
.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
}