What are the thread states in Java, and how does a thread move between them?
There are six states, and they are defined by the enum Thread.State.
NEW means the thread object has been made but the method start has not been called yet. The thread has not run any code.
RUNNABLE means the thread is either running or it is ready to run. Java puts those two together, because a thread that is ready to run is waiting for the processor and there is no way to tell the difference from the outside.
BLOCKED means the thread is waiting for a monitor lock, which is the lock that a synchronized method or block uses.
WAITING means the thread is waiting for something to happen, with no time limit. It is waiting for a notification, or for another thread to finish.
TIMED_WAITING means the same thing but with a deadline. A thread that is sleeping is in this state.
TERMINATED means the thread has finished and cannot be started again.
So how does a thread move between them? It starts in NEW, and the call to start moves it to RUNNABLE. From there it moves to BLOCKED when it cannot get a monitor lock, to WAITING when it waits for a notification, and to TIMED_WAITING when it waits with a deadline. It goes back to RUNNABLE when the thing it was waiting for happens, and it ends in TERMINATED when its work is done.
One detail is worth knowing. The state TIMED_WAITING does not include a thread that is waiting to enter a synchronized block with a timeout, because that thread is BLOCKED while it waits and it does not get to check the clock. The timeout only takes effect once it has the lock.
The next question in this topic looks at how to see these states while the program is running.