Search code examples
javathreadpoolthreadpoolexecutor

How can I shut down a Thread Pool correctly by use a while loop


Here is some main code of my question,I'm a Student in China,My English is not good, please the excuse me.

public static void main(String[] args) {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Thread-%d").build();
    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            5, 10, 0, TimeUnit.SECONDS, new SynchronousQueue<>(),
            threadFactory, new ThreadPoolExecutor.DiscardPolicy()
    );
    // I submit 10 short task here
    // 👇I want when ThreadPool finish 10 task, then shut down the pool👇
    while (!poolExecutor.isTerminated() && poolExecutor.getCompletedTaskCount() == 10) {
        poolExecutor.shutdown();
    }
}

I want when ThreadPool finish 10th task, then shut down the pool,but the while loop does not seems to execute,the main Thread has been finished,but the core Thread of ThreadPool is still Waiting for task。

If I do not use the while loop and directly use poolExecutor.shutdown();. I can get the expected results. All the threads are finished and shutdown correctly. But I want to know what's the error of my code.


Solution

  • I have solved my question, It just a logic error, Sorry waste everyone's time, the correct code is that:

    public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Thread-%d").build();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                5, 10, 0, TimeUnit.SECONDS, new SynchronousQueue<>(),
                threadFactory, new ThreadPoolExecutor.DiscardPolicy()
        );
        while (!poolExecutor.isTerminated()) {
            if (poolExecutor.getCompletedTaskCount() == 10) {
                poolExecutor.shutdown();
            }
            
        }
    }
    

    If I use the logical expression !poolExecutor.isTerminated() && poolExecutor.getCompletedTaskCount() == SORT_ALGORITHM_SIZE in while loop, It will probably beacause true && false and exit the loop. Then I can't close the thread pool

    Thank you again for your help.