Java8 异步CompletableFuture 用法

1.核心代码 CompletableFuture> 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> onlineShopNoFuture = CompletableFuture.supplyAsync(() -> getMap());
        System.out.println("异步方法执行后,时间 = "+df.format(LocalDateTime.now(ZoneOffset.of("+8")))+ Thread.currentThread().getName());
        try {
            Map 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 getMap(){
        try {
            System.out.println("123"+ Thread.currentThread().getName());
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map map = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            map.put(i+"",i+"");
        }
        return map;
    }

Java8 异步CompletableFuture 用法_第1张图片

你可能感兴趣的:(java,java)