public static void main(String[] args) throws ExecutionException, InterruptedException {
List<CompletableFuture<String>> futures = new ArrayList<>();
long totalstart = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
//任务交给线程池后,线程就已经开始执行了。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return " sucess";
});
futures.add(future);
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < futures.size(); i++) {
long start = System.currentTimeMillis();
//这里只是获取结果。
String s = futures.get(i).get();
long end = System.currentTimeMillis();
long time = end - start;
System.out.println("第" + i + "个执行了 " + time + "ms");
}
long totalEnd = System.currentTimeMillis();
long totalTime = totalEnd-totalstart;
System.out.println(" 共执行了 " + totalTime + "ms");
}
```
结果
```
第0个执行了 0ms
第1个执行了 0ms
第2个执行了 0ms
第3个执行了 0ms
第4个执行了 0ms
结论: 当创建Future时,已经把任务给到了线程池,线程开始调度并执行任务了。 get()只会同步返回结果
146

被折叠的 条评论
为什么被折叠?



