Java Reference
In-Depth Information
Thread States
A thread takes on various states from the time that it starts to the point when its
run
method completes execution. You should be able to recognize the various thread states and
how a thread transitions from one state to another. This section discusses the details of
these various states.
The
Thread
class defi nes the following method for obtaining the current state of a
thread:
public Thread.State getState()
Thread.State
is an enumeration defi ned in the
Thread
class that represents all the
possible states of threads. The
Thread.State
enumeration has the following values:
NEW
The thread has been instantiated but not started yet.
RUNNABLE
The thread is either currently running on the CPU or waiting to be scheduled by
the JVM for execution.
BLOCKED
The thread is waiting for a monitor lock to become available. A thread becomes
blocked when attempting to enter a block of synchronized code.
WAITING
The thread is waiting for another thread to perform a particular action. For
example, the thread might be waiting for another thread to call
Object.notify
on a spe-
cifi c object or waiting for another thread to terminate due to a call to
Thread.join
.
TIMED_WAITING
This state is similar to
WAITING
except the thread only waits until a speci-
fi ed time elapses. A thread enters this state with a call to
Thread.join
or
Object.notify
with a timeout, or
Thread.sleep
.
TERMINATED
The thread has run to completion. A terminated thread cannot be started
again.
Now we discuss each of these states and how a thread transitions from one state to
another.
New Threads
A
Thread
object is required to create a thread in Java. After a
Thread
object is
instantiated but before its
start
method is invoked, the thread is referred to as being in
the
new thread
state. Let's look at an example. Suppose we have the following
Runnable
Search WWH ::
Custom Search