1.核心代码 CompletableFuture<Map<String, String>> onlineShopNoFuture = CompletableFuture.supplyAsync(() -> getMap());
2.异步执行getMap方法,实际中可异步查询数据库,异步处理复杂逻辑, 可用于优化代码,提高效率
public static void main(String[] args) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println("开始执行,时间 = "+df.format(LocalDateTime.now(ZoneOffset.of("+8"))) + Thread.currentThread().getName());
CompletableFuture<Map<String, String>> onlineShopNoFuture = CompletableFuture.supplyAsync(() -> getMap());
System.out.println("异步方法执行后,时间 = "+df.format(LocalDateTime.now(ZoneOffset.of("+8")))+ Thread.currentThread().getName());
try {
Map<String, String> map = onlineShopNoFuture.get();
log.info("comple开始执行,时间 = {}",df.format(LocalDateTime.now(ZoneOffset.of("+8"))));
for (int i = 0; i < 10; i++) {
String s = map.get(i + "");
System.out.println(s);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static Map<String, String> getMap(){
try {
System.out.println("123"+ Thread.currentThread().getName());
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Map<String, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(i+"",i+"");
}
return map;
}