Java线程池如何复用线程?是否存在额外线程状态?
Great question! Let's break this down clearly, since it's a common point of confusion when learning about Java thread pools.
Thread Pool Worker Thread Reuse Mechanism
When a worker thread in a thread pool finishes executing its current task, it doesn't immediately transition to the TERMINATED state. Instead, it enters a loop that waits for new tasks to process—this is the core of thread reuse.
Under the hood (take ThreadPoolExecutor, the most common thread pool implementation, as an example), each worker thread is wrapped in a Worker class. The run() method of this Worker calls runWorker(), which contains a key loop:
while ((task = getTask()) != null) { // Execute the task task.run(); } // Exit the loop and terminate the thread
The getTask() method is where the magic happens:
- It attempts to fetch the next task from the thread pool's task queue (usually a
BlockingQueue). - If the queue is empty, the thread will block:
- For core threads (when
allowCoreThreadTimeOutisfalse), it usesqueue.take()which blocks indefinitely—putting the thread in theWAITINGstate. - For non-core threads or core threads with timeouts enabled, it uses
queue.poll(timeout, unit)which blocks for a set period—putting the thread inTIMED_WAITINGstate.
- For core threads (when
- When a new task is added to the queue, the blocking call is interrupted/woken up, the thread transitions back to
RUNNABLE, and executes the new task. getTask()only returnsnullwhen the thread needs to be terminated (e.g., thread pool is shutting down, or the pool has more threads than the core size and the idle timeout has passed). At that point, the loop exits, and the thread finally moves toTERMINATED.
Do Thread Pools Introduce Extra Thread States?
Short answer: No, the worker threads themselves still use the standard Thread.State enum values (NEW, RUNNABLE, WAITING, TIMED_WAITING, BLOCKED, TERMINATED).
What can be confusing is that the thread pool itself has its own set of states (defined in ThreadPoolExecutor):
RUNNING: Accept new tasks and process queued tasks.SHUTDOWN: Don't accept new tasks, but process queued tasks.STOP: Don't accept new tasks, don't process queued tasks, and interrupt in-progress tasks.TIDYING: All tasks have terminated, worker count is 0, transitioning to TERMINATED.TERMINATED: Termination complete.
These are states of the pool as a whole, not the individual worker threads. Each worker thread's state still follows the standard Thread.State definitions based on what it's doing (waiting for a task, executing a task, etc.).
内容的提问来源于stack exchange,提问作者shankulk

