Java8 异步CompletableFuture 用法

文章展示了如何利用Java中的CompletableFuture类进行异步操作,例如异步执行getMap方法,该方法模拟了查询数据库或处理复杂逻辑的过程。在主线程中,CompletableFurure供应链被创建并立即返回,允许后续代码继续执行,而不等待getMap的完成。当getMap完成后,结果会被获取并处理,提高了程序的运行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值