Life circle of Thread

ht‮www//:spt‬.theitroad.com

In Java, a thread goes through several states during its lifetime. Here are the different states in the order in which they occur:

  1. New: When a thread is created but has not yet started, it is in the new state.

  2. Runnable: When a thread is ready to run, it moves to the runnable state. In this state, the thread is waiting to be assigned to a processor by the operating system.

  3. Running: When the operating system assigns a processor to the thread, it enters the running state. In this state, the thread is actively executing its code.

  4. Blocked: If a thread is waiting for a resource that is currently unavailable, it moves to the blocked state. In this state, the thread is not executing any code, and it will not be assigned to a processor until the resource it is waiting for becomes available.

  5. Waiting: If a thread is waiting for a specific condition to occur, it moves to the waiting state. In this state, the thread is not executing any code, and it will not be assigned to a processor until the condition it is waiting for occurs.

  6. Timed Waiting: If a thread is waiting for a specific condition to occur, but with a time limit, it moves to the timed waiting state. In this state, the thread is not executing any code, and it will not be assigned to a processor until the condition it is waiting for occurs or the time limit is reached.

  7. Terminated: When a thread has completed its work or has been terminated, it moves to the terminated state. In this state, the thread is no longer running, and it cannot be restarted.

Note that not all threads will go through every state. For example, a thread that completes its work quickly may only be in the new, runnable, running, and terminated states, while a thread that is waiting for a resource to become available may go through the blocked and runnable states before moving to the running state.