Java Reference
In-Depth Information
Life Cycle of a Thread
A thread is always in one of the following six states:
New
Runnable
Blocked
Waiting
Timed-waiting
Terminated
All these states of a thread are JVM states. They do not represent the states assigned to a thread by an
operating system.
When a thread is created and its start() method is not yet called, it is in the new state.
Thread t = new SomeThreadClass(); // t is in the new state
A thread that is ready to run or running is in the runnable state. In other words, a thread that is eligible for getting
the CPU time is in a runnable state.
the JVM combines two Os-level thread states: ready-to-run and running into a state called the runnable state.
a thread in the ready-to-run Os state means it is waiting for its turn to get the CpU time. a thread in the running Os state
means it is running on the CpU.
Tip
A thread is said to be in a blocked state if it was trying to enter (or re-enter) a synchronized method or block but
the monitor is being used by another thread. A thread in the entry set that is waiting to acquire a monitor lock is in the
blocked state. A thread in the wait set that is waiting to reacquire the monitor lock after it has been woken up is also in
a blocked state.
A thread may place itself in a waiting state by calling one of the methods listed in Table 6-2 . A thread may
place itself in a timed-waiting state by calling one of the methods listed in Table 6-3 . I will discuss the usage of the
parkNanos() and parkUntil() methods later in this chapter.
Table 6-2. Methods That Place a Thread in Waiting State
Method
Description
wait()
This is the wait() method of the Object class, which a thread may call if it wants to wait for a specific
condition to hold. Recall that a thread must own the monitor's lock of an object to call the wait()
method on that object. Another thread must call the notify() or notifyAll () method on the same
object in order for the waiting thread to transition to the runnable state.
join()
This is the join() method of the Thread class. A thread that calls this method wants to wait until the
thread on which this method is called terminates.
park()
This is the park() method of the LockSupport class, which is in the java.util.concurrent.locks
package. A thread that calls this method may wait until a permit is available by calling the unpark()
method on a thread. I will cover the LockSupport class later in this chapter.
 
Search WWH ::




Custom Search