static ThreadPoolExecutor executor = new ThreadPoolExecutor( Runtime.getRuntime().availableProcessors() * 2, (int)(Runtime.getRuntime().availableProcessors() /0.1), 120, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000)); public static void main(String[] args) { List<Integer> numberList = IntStream.rangeClosed(1, 10) .boxed() // 将int转换为Integer .toList(); CompletableFuture<Void> voidCompletableFuture = taskA(numberList) .thenRun(() -> taskB(numberList).join()) // 此处和下面两行可以去掉join()测试观察异同 .thenRun(() -> taskC(numberList).join()) .thenRun(() -> taskD(numberList).join()) .thenRunAsync(() -> { executor.shutdown(); }); // voidCompletableFuture.join(); } private static CompletableFuture<Void> taskD(List<Integer> numberList) { System.out.println(); List<CompletableFuture<Void>> futureList = numberList.stream().map(x -> CompletableFuture.runAsync(() -> { try { Thread.sleep(2000); System.out.print("taskD--" + x); } catch (InterruptedException e) { throw new RuntimeException(e); } }, executor)).toList(); return CompletableFuture.allOf( futureList.toArray(new CompletableFuture[0]) ); } private static CompletableFuture<Void> taskC(List<Integer> numberList) { System.out.println(); List<CompletableFuture<Void>> futureList = numberList.stream().map(x -> CompletableFuture.runAsync(() -> { try { Thread.sleep(2000); System.out.print("taskC--" + x); } catch (InterruptedException e) { throw new RuntimeException(e); } }, executor)).toList(); return CompletableFuture.allOf( futureList.toArray(new CompletableFuture[0]) ); } private static CompletableFuture<Void> taskB(List<Integer> numberList) { System.out.println(); List<CompletableFuture<Void>> futureList = numberList.stream().map(x -> CompletableFuture.runAsync(() -> { try { Thread.sleep(2000); System.out.print("taskB--" + x); } catch (InterruptedException e) { throw new RuntimeException(e); } }, executor)).toList(); return CompletableFuture.allOf( futureList.toArray(new CompletableFuture[0]) ); } private static CompletableFuture<Void> taskA(List<Integer> numberList) { System.out.println(); List<CompletableFuture<Void>> futureList = numberList.stream().map(x -> CompletableFuture.runAsync(() -> { try { Thread.sleep(2000); System.out.print("taskA--" + x); } catch (InterruptedException e) { throw new RuntimeException(e); } }, executor)).toList(); return CompletableFuture.allOf( futureList.toArray(new CompletableFuture[0]) ); }
执行结果

浙公网安备 33010602011771号