/* related posts with thumb nails */

Life Cycle of a Thread:

During the life time of a thread, there are many states it can enter. They include:
1.      Newborn state
2.      Runnable state
3.      Running state
4.      Blocked state
5.      Dead state


Newborn State: When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:
          Schedule it for running using start() method.
          Kill it using stop() method.
If scheduled, it moves to the runnable state If we attempt to use any other method at this stage, an exception will be thrown. This state is achieved when we create instances of a thread class. Ex:  MyThread  t = MyThread();

Runnable State: The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e., first-come, first-serve manner. After its turn, the thread joins the queue again and waits for next turn. This process of assigning time to threads is known as time-slicing. This state is achieved when we invoke start() method or threads revive their control by resume(), or notify() methods or after the elapse of certain time set by sleep() method.

Running State: Running means that the processor has given its time to the thread for its execution. The thread runs until it gives up control on its own or taken over by other threads. When the thread is in its running state, we can ensure that the control is in run() method of the thread.

Blocked State: A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently to the running state. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered "not runnable" but not dead and therefore fully qualified to run again. This state is achieved when we invoke suspend() or sleep() or wait() methods.

Dead State: Every thread has a life cycle. A running thread ends its life when it has completed executing its run( ) method. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running, or even when it is in "not runnable" (blocked) condition. This state is achieved when we invoke stop() method or the thread completes it execution.

Related Topics:

0 comments:

Post a Comment