CompletableFuture for循环生成

该博客展示了如何在Java中利用CompletableFuture的supplyAsync方法进行异步接口调用,以提高程序效率。博主创建了一个包含100个任务的列表,每个任务都在单独的线程中执行并延迟1秒,然后通过CompletableFuture的allOf方法等待所有任务完成。最后,博主展示了如何获取并打印所有任务的结果,以及计算整个过程的时间消耗,以此说明异步处理在提升并发性能上的优势。
摘要由CSDN通过智能技术生成
package com.example.demo.util.CompletableFuture;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureFor {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        List<CompletableFuture<?>> futures = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            futures.add(CompletableFuture.supplyAsync(() ->
                    {
                        try {
                            Thread.sleep(1000);
                            System.out.println("线程:CompletableFuture" + Thread.currentThread().getName());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return finalI;
                    }
            ));
        }
        //等待全部完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        //获取内容
        for (CompletableFuture<?> future : futures) {
            try {
                Object s = future.get();
                System.out.println(s);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("主线程:" + Thread.currentThread().getName());

        System.out.println("cost" + (end - start));
    }

}

最近项目中需要循环调用 一个接口,考虑到提高效率使用了CompletableFuture  supplyAsync方法进行异步调用。

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值