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