When a thread is executed it changes its state. A thread can be in any one of the five thread states. According to Sun Microsystem, a thread has only 4 states, such as: new , runnable, non-runnable and terminated state. For better understanding the thread concept we will see the 5 different states of any thread in java.
Java Virtual Machine plays an important role in controlling the life cycle of a thread. The following are different life cycle of thread states:
- Non-Runnable (Blocked)
- When we create a Thread class object, it is said to be in new state.
- It is a state where a thread is not yet scheduled for running.
- It is a state before the invocation of start ( ) method.
- The runnable state defines that the thread is ready for execution and is waiting for the processor.
- Runnable state means that the thread is about to begin its task and waiting for execution.
- The threads waiting for execution are handled by thread scheduler and decides the scheduling techniques such as: FCFS, Round Robin, Priority-based scheduling, etc.
- When a thread has been selected by the thread scheduler for execution then it is said to be in running state.
- Any thread is said to be in running state till it is not affected by any exception or sleep ( ) or any high priority threads or suspended for some I/O operations.
4. Non-Runnable ( Blocked )
- A thread is said to be in non-runnable or blocked state when it is prevented from entering into the runnable state and subsequently to the running state.
- In non-runnable state a thread is still alive but it is not currently eligible to run.
- A thread is said to be “non-runnable” state when the thread is made suspended , sleeped, or made wait for a long time for some input/output event to be completed.
- A thread is said to be in terminated state when it has completed its execution i.e. when it exits from run ( ) method.
- When a thread it created and completed its task then it it terminated and it is referred to as natural death of the thread.
- A thread is terminated at any point of time from its creation to its execution or suspension by sending the stop message to it and it is referred to as premature death of the thread.
- A thread can be killed as soon as it is born or created, or while it is running, or even when it is in “non-runnable” (blocked) state.