Monday, 25 April 2016

What are the Thread states ? (Life cycle of Java Thread)


Life cycle of Java Thread




New state
After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.

Runnable (Ready) state
A thread start its life from Runnable state.
A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also.
On this state a thread is waiting for a turn on the processor.

Running state
A thread is in running state that means the thread is currently executing.
There are several ways to enter in Runnable state but there is only one way to enter in Running state:
The scheduler select a thread from runnable pool.

Dead state
A thread can be considered dead when its run() method completes.
If any thread comes on this state that means it cannot ever run again.

Blocked state
A thread can enter in this state because of waiting the resources that are hold by another thread.



Conditions for blocked state
Sleeping
On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time.
You can use the method sleep( ) to stop the running state of a thread.
     static void sleep(long millisecond) throws InterruptedException

Waiting for Notification
A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread.    
     final void wait(long timeout) throws InterruptedException
     final void wait(long timeout, int nanos) throws InterruptedException
     final void wait() throws InterruptedException

Blocked on I/O
The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources.

Blocked for joint completion
The thread can come on this state because of waiting the completion of another thread.

Blocked for lock acquisition
The thread can come on this state because of waiting to acquire the lock of an object.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.