Friday, March 1, 2013

Java Thread states

Thread States

Thread schedulers job is to move in and out of the running state. While thread sheduler can move a thread from running state to runnable but if thread move out of running state it will not back to runnable. So when the threads run() method completes the thread directly moves from running state to dead state.

A thread can be in any one of the below 5 states.

1. New
2. Runnable
3. Running
4. Wainting/blocked/sleeping
5. Dead

Lets see about these thread states with some more details.

New:

This state is in thread when Thread instance has been created but start() method has not been invoked.
This is a live thread object but not yet entered in to a runnable state. So this thread is considered as not alive.

Runnable:

In this state, when a thread eligible to run, but the scheduler not selected to be the running thread.
A thread first enters the runnable state when the start() method is invoked but a thread can also return to the runnable state after either running or coming back from wainting, blocked or sleeping state.

So when a thread is in the runnable, the thread is considered alive.

Running:

      In this state the scheduler selects the thread which is in runnable state from thread pool to excecute the process.

Waiting/blocked/sleeping:

This is the state a thread is in when its eligible to run. This is really a three states combined in to one but they all have one thing in common: the thread is still alive, but not eligible to run. In other words its not runnable but it might return to runnable state later if particular event occurs.

A thread may be blocked waiting for a resource, in which case the event sends it back to runnable is the availability of the resource.
A thread may be sleeping because the threads run code tells it to sleep for some period of time in ehich case the event that sends it back to the runnable is that it wake up because it sleep time has expired.

Or the thread may be waiting, because the threads run code causes it to wait, in which case the event that sends it back to runnable is that another thread sends a notification that it may no longer be necessary for the thread to wait.
The important point is that the thread does not tell another thread to block.

Dead:
A thread is considered thread when its run() method completes. Once a thread is dead it can never be brought back to life.

 

      
 




No comments: