Java Reference
In-Depth Information
A new thread begins its life cycle in the
new
state. It remains in this state until the program
starts the thread, which places it in the
runnable
state. A thread in the
runnable
state is
considered to be executing its task.
Sometimes a
runnable
thread transitions to the
waiting
state while it waits for another
thread to perform a task. A
waiting
thread transitions back to the
runnable
state only when
another thread notifies it to continue executing.
A
runnable
thread can enter the
timed waiting
state for a specified interval of time. It tran-
sitions back to the
runnable
state when that time interval expires or when the event it's
waiting for occurs.
Timed waiting
threads and
waiting
threads cannot use a processor, even
if one is available. A
runnable
thread can transition to the
timed waiting
state if it provides
an optional wait interval when it's waiting for another thread to perform a task. Such a
thread returns to the
runnable
state when it's notified by another thread or when the timed
interval expires—whichever comes first. Another way to place a thread in the
timed waiting
state is to put a
runnable
thread to sleep—a
sleeping thread
remains in the
timed waiting
state for a designated period of time (called a
sleep interval
), after which it returns to the
runnable
state. Threads sleep when they momentarily do not have work to perform. For
example, a word processor may contain a thread that periodically backs up (i.e., writes a
copy of) the current document to disk for recovery purposes. If the thread did not sleep
between successive backups, it would require a loop in which it continually tested whether
it should write a copy of the document to disk. This loop would consume processor time
without performing productive work, thus reducing system performance. In this case, it's
more efficient for the thread to specify a sleep interval (equal to the period between suc-
cessive backups) and enter the
timed waiting
state. This thread is returned to the
runnable
state when its sleep interval expires, at which point it writes a copy of the document to disk
and reenters the
timed waiting
state.
A
runnable
thread transitions to the
blocked
state when it attempts to perform a task that
cannot be completed immediately and it must temporarily wait until that task completes.
For example, when a thread issues an input/output request, the operating system blocks
the thread from executing until that I/O request completes—at that point, the
blocked
thread transitions to the
runnable
state, so it can resume execution. A
blocked
thread can-
not use a processor, even if one is available.
A
runnable
thread enters the
terminated
state (sometimes called the
dead
state) when it
successfully completes its task or otherwise terminates (perhaps due to an error). In the
UML state diagram of Fig. 23.1, the
terminated
state is followed by the UML final state
(the bull's-eye symbol) to indicate the end of the state transitions.