Thread Life Cycle-tutorial
In Java Thread always exists in any one of the following states:
- New
- Active
- Blocked/Waiting
- Timed Waiting
- Terminated
- New: Whenever a new Thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution.
- Active: When a thread invokes a start() method it moves from the new state to the active state. The active state contains two states within it i.e. Runnable and Running
- Runnable: A thread that is ready to run is then moved to the runnable state, In the runnable state the thread may be running or ready to run at any instant of time It is the duty of the thread scheduler to provide the Thread time to run i.e. moving the thread the running state.
- Running: When the thread gets the CPU, it moves from runnable to the running state.
- Blocked or waiting: Whenever a thread is inactive for a span of time (Not permanently) then, either the thread is in the blocked state or in the waiting state. If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler.
- Timed waiting: Sometimes, Waiting leads to starvation, For example, a thread (say A) has entered the critical section of a code and is not willing to leave that critical section in such a scenario, another thread (say B) has to wait forever, which leads to starvation. To avoid such a scenario Timed waiting is given to thread B. Thus thread lies in the waiting state.
- Terminated: A thread reaches the termination state because of the following reasons:
1. When a thread has finished its job, then it terminates normally
2. Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation faults.