CompletableFuture for循环生成

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) {
		//循环调用方法
        List<CompletableFuture<?>> futures = new ArrayList<>();
		for(int y = 1;y < 10;y++){
			futures.add(CompletableFuture.supplyAsync(() ->{
				try {
					Thread.sleep(1000);
					List<String> result = query(y,1000);
					return result;
				}catch (InterruptedException e) {
					e.printStackTrace();
				}
			}));
		}
		

		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(newCompletableFuture[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方法进行异步调用。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值