package com.fwkily.practice.threadpool; import java.util.concurrent.* ; /** * @Author : fuwk * @Description : * @Date : 18:08 2022/1/6 */ public class Test { public static void main(String[] args) { final ExecutorService EXECUTOR_BILL = new ThreadPoolExecutor(Runtime. getRuntime().availableProcessors() * 2, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy()); CompletionService<Boolean> CompletionService = new ExecutorCompletionService<>(EXECUTOR_BILL); CountDownLatch countDownLatch = nouveau CountDownLatch(10); pour (int je = 0; je < 10; je++) { int finalI = je ; completeService.submit(() -> { new Thread(() -> System.out.println("线程" + finalI + "执行任务"),"线程" + finalI).start(); try { Thread.sleep (1000); } catch (InterruptedException e) { e.printStackTrace(); }finally { countDownLatch.countDown(); } return true; }); } for (int i = 0; i < 10; i++) { try { Boolean aBoolean = CompletionService.take().get(); System.out.println("Renvoyer le résultat" + aBoolean); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } System.out.println("Les tâches sont prêtes !"); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Ceci est le thread principal pour effectuer les tâches suivantes!"); // Quittez le pool de threads --- assurez-vous d'arrêter le pool de threads, sinon le thread principal ne se terminera pas EXECUTOR_BILL. shutdown(); } } Le thread principal n'est pas terminé
Rejoignez l'arrêt, quittez le pool de threads, le thread principal est terminé