Java Reference
In-Depth Information
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. What I want to do now is discuss these var-
ious stages of a thread's life:
Born. When a thread is first created, it is referred to as a born thread.
Every thread has a priority, with a new thread inheriting the priority of
the thread that created it. This priority can be changed at any time in the
thread's life cycle. Thread priority is an int value, and your Java threads
can have any priority between 1 and 10. A born thread does not run until
it is started.
Runnable. After a newly born thread is started, the thread becomes
runnable . For each of the 10 priorities, there is a corresponding priority
queue (the first thread in is the first thread out). When a thread becomes
runnable, it enters the queue of its respective priority. For example, the
main() thread has the normal thread priority, which is 5. If main() starts
a thread Y, then Y enters the priority 5 queue. If Y starts a thread Z and
assigns Z a priority of 8, Z will enter the priority 8 queue. If Z is the
highest-priority thread, it will preempt the current thread and start run-
ning immediately.
Keep in mind that the Java thread scheduler is preemptive . If the priority 5
queue has two runnable threads in it, say X and Y, and these threads are
the highest priority of all other threads, X and Y will dominate the CPU. If
a priority 8 thread comes along, say Z, it will immediately preempt the
currently running priority 5 thread and start running. The X and Y threads
must now wait until the Z thread is no longer runnable.
Running. The thread scheduler determines when a runnable thread gets
to actually run. In fact, the only way a thread is running is if the thread
scheduler grants it permission. If for any reason a thread has to give up
the CPU, it must eventually work its way through the runnable priority
queues before it can run again.
Blocked. A thread can become blocked, which occurs when multiple
threads are synchronizing on the same data and need to take turns. A
blocked thread is not running, nor is it runnable. It waits until the syn-
chronization monitor allows it to continue, at which point it becomes
runnable again and enters its appropriate priority queue.
Search WWH ::




Custom Search