1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public class CompletableFutureTest5 {
@SneakyThrows public static void main(String[] args) { int processors = Runtime.getRuntime().availableProcessors(); ThreadPoolExecutor executor = new ThreadPoolExecutor( processors+1, processors+1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy() );
CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> "任务1", executor); CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> "任务2", executor); CompletableFuture<String> future03 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return "任务3"; }, executor);
CompletableFuture<Void> all = CompletableFuture.allOf(future01, future02, future03); all.join(); all.get(); } }
|