Lifecycle of thread in java - Java @ Desk

Monday, June 3, 2013

Lifecycle of thread in java

Thread can be create either by creating an object of java.lang.Thread() class or by implementing a Runnable interface.

The lifecycle of thread includes various states as explained below:



New: The thread enters in this state when the new object of Thread class is created. The thread in this state is not yet considered for running.

Runnable: When a start() method is called on the thread object created in step 1, the thread enters in this state. The other routes from where the thread can enter into this state are running, waiting, blocked, sleep

Running: In this state, the thread actually is in execution mode. Thread enters in this state when the scheduler selects this thread object from the runnable pool

Dead: It’s a last state in a lifecycle of a thread. 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 - A thread can enter in this state because of waiting the resources that are hold by another thread. Thread can be moved to this state using wait, sleep, suspend operations.

Sleeping: The thread enters into this state when sleep() method is called on that. This is normally done to slow down the process of thread. In this state, the thread sleeps for specified amount of time and then enters into Runnable state.

Waiting: There are times when a thread needs to wait for another thread to finish first before it can continue. For instance, if two threads share the same resource, and one of the two is holding that resource, then the other thread needs to wait for that resource to be released.

Other references on threads
Difference between sleep and wait in java
Lifecycle of thread
Difference between yield and sleep in java
Thread creation in java







No comments:

Post a Comment