multi threading
intermediateThread Lifecycle
Know the six states a Java thread moves through, and what causes each transition.
Every Java thread is, at any instant, in exactly one of six states defined by the Thread.State enum, and the transitions between them are driven by the methods you call and the locks and conditions the thread is waiting on. Being able to name the states and what moves a thread between them is the foundation for reasoning about deadlocks, liveness, and why a thread "isn't running."
A guest at a restaurant — arrived (NEW), seated and eating (RUNNABLE), waiting for the bathroom (BLOCKED), waiting for a friend (WAITING), nap with an alarm (TIMED_WAITING), left (TERMINATED).
Key Concepts
1
A thread starts in NEW once constructed but before start(). Calling start() moves it to RUNNABLE, which covers both actually executing on a CPU and being ready and waiting for one — Java does not distinguish "running" from "ready to run." From there it can enter BLOCKED while waiting to acquire a monitor lock held by another thread (for example at the boundary of a synchronized block). It enters WAITING when it calls wait(), join(), or park() with no timeout, parking indefinitely until another thread signals it. TIMED_WAITING is the same idea but bounded — sleep(ms), wait(ms), or join(ms). When the run() method completes or throws, the thread reaches TERMINATED and cannot be restarted.
NEWstart()RUNNABLEBLOCKEDsynchronized
2
The distinctions carry real weight in interviews. BLOCKED specifically means "waiting for a lock," whereas WAITING/TIMED_WAITING mean "waiting to be notified or for a timer" — confusing them muddles deadlock analysis. sleep() holds any locks it already owns while pausing, but wait() releases the monitor it was called on, which is the whole point of the wait/notify mechanism. And because RUNNABLE includes threads blocked on I/O at the OS level, a thread can appear runnable while making no progress.
BLOCKEDWAITINGTIMED_WAITINGsleep()wait()