CompletableFuture的并行用法
final static ExecutorService executor = new ThreadPoolExecutor(10, 20, 0L, TimeUnit.MINUTES, new LinkedBlockingDeque());
@Test
public void test3() {
long l = System.currentTimeMillis();
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> {
try {
System.out.println(test());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executor),
CompletableFuture.runAsync(() -> {
try {
System.out.println(test());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executor),
CompletableFuture.runAsync(() -> {
try {
System.out.println(test());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executor),
CompletableFuture.runAsync(() -> {
try {
System.out.println(test());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executor)
).join();
System.out.println(System.currentTimeMillis() - l);
}
private String test() throws InterruptedException {
Thread.sleep(1000);
return "test";
}
最后执行时间1000毫秒;
他是同时执行这四块,执行时间就是这四块中最慢执行完的时间.