Active thread count doesn't decrements even after the thread closes

user1 :

In the below code, Thread.activeCount() returns 2 always even though the thread in executor terminates after 5 seconds.

public class MainLoop {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(12);
        executor.submit(new Callable<Void>() {
            public Void call() throws Exception {
                Thread.sleep(5000);
                return null;
            }
        });
        while (true) {
            System.out.println(Thread.activeCount());
            Thread.sleep(1000);
        }
    }
}

I expected Thread.activeCount() to return 1 after 5 seconds. Why is it always returning 2 ?

Lesiak :

See the docs of newFixedThreadPool. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)

At any point, at most nThreads threads will be active processing tasks. The threads in the pool will exist until it is explicitly shutdown.

After a callable is submitted to this executor, it will be pricked up and processed by one of the threads of the pool. After completing this execution, the thread will sit idle in the pool waiting for a next callable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142948&siteId=1