Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
What do you think the output will be if you run the ThreadTester class? (we’ll find out in a few pages)
The three states of a new thread
But there’s more. Once the thread becomes runnable, it can move back and forth between runnable, running, and an additional state: temporarily not runnable (also known as ‘blocked’).
Typically, a thread moves back and forth between runnable and running, as the JVM thread scheduler selects a thread to run and then kicks it back out so another thread gets a chance.
A thread can be made temporarily not-runnable
The thread scheduler can move a running thread into a blocked state, for a variety of reasons. For example, the thread might be executing code to read from a Socket input stream, but there isn’t any data to read. The scheduler will move the thread out of the running state until something becomes available. Or the executing code might have told the thread to put itself to sleep (sleep()). Or the thread might be waiting because it tried to call a method on an object, and that object was ‘locked’. In that case, the thread can’t continue until the object’s lock is freed by the thread that has it.