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 = new CountDownLatch(10); for (int i = 0; i < 10; i++) { int finalI = i; completionService.submit(() -> { new Thread(() -> System.out.println("thread" + finalI + "execution task"),"thread" + 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("return result" + aBoolean); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } System.out.println("Tasks are ready!"); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "This is the main thread to perform the following tasks!"); //Exit the thread pool --- be sure to shutdown the thread pool, otherwise the main thread will not end EXECUTOR_BILL.shutdown(); } } The main thread has not ended
Join shutdown, exit the thread pool, the main thread has ended