前置知识
1,CompletableFuture 使用supplyAsync 可以直接执行,并得到返回结果
2,CompletableFuture get方法,可以得到最终的结果
代码
private void foreachGet() throws ExecutionException, InterruptedException {
Random random = new Random();
long mainstart = System.currentTimeMillis();
List<CompletableFuture<String>> futureList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread()+",begin");
long start = System.currentTimeMillis();
int time = random.nextInt(3000);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(Thread.currentThread()+",cost:"+(end - start));
System.out.println(Thread.currentThread()+",end");
return time+"";
});
futureList.add(future);
}
for (CompletableFuture<String> future : futureList) {
future.get();
}
long mainend = System.currentTimeMillis();
System.out.println(Thread.currentThread()+" is end:"+(mainend - mainstart));
}