ExecutorService executorService = Executors.newFixedThreadPool(8);
CompletableFuture<Integer> firstFuture = CompletableFuture.supplyAsync(() -> {
log.info("开始执行第一个任务");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
}, executorService);
CompletableFuture<Integer> secondFuture = CompletableFuture.supplyAsync(() -> {
log.info("开始执行第二个任务");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 2;
}, executorService);
CompletableFuture<Integer> thirdFuture = CompletableFuture.supplyAsync(() -> {
log.info("开始执行第三个任务");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
}, executorService);
try {
Integer first = firstFuture.get();
log.info("first:{}", first);
Integer second = secondFuture.get();
log.info("second:{}", second);
Integer third = thirdFuture.get();
log.info("third:{}", third);
} catch (Exception e) {
e.printStackTrace();
}
未完待续。。。
参考:https://mp.weixin.qq.com/s/VCRtwaJ99p5FzBl0xlClIg