Two ways to judge the end of the thread pool

Posted Jun 16, 20201 min read

shutdown() + awaitTermination()

public class Test {
    public static int threadNum = 10;
    public static void main(String[]args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        for(int i = 0; i < threadNum; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    //do work
                }
            });
        }
     executorService.shutdown();
     executorService.awaitTermination(1,TimeUnit.HOURS);
    }
}

CountDownLatch

public class Test {
    public static int count = 0;
    public static int threadNum = 10;
    public static void main(String[]args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        CountDownLatch countDownLatch = new CountDownLatch(threadNum);
        for(int i = 0; i < threadNum; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    //do work
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
    }
}