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