The life cycle of a Java Thread
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
- Non-Runnable (Blocked)
- Dead (Terminated)
1. Newborn :
When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not alive and it’s a state internal to Java programming.
When we call the start() function on the Thread object, its state is changed to Runnable. The control is given to the Thread scheduler to finish its execution. Whether to run this thread instantly or keep it in a runnable thread pool before running, depends on the OS implementation of the thread scheduler.
When a thread is executing, its state is changed to Running. Thread scheduler picks one of the threads from the runnable thread pool and changes its state to Running. Then CPU starts executing this thread. A thread can change state to Runnable, Dead, or Blocked from running state depends on time slicing, thread completion of the run() method, or waiting for some resources.
A thread can be waiting for other threads to finish using thread join or it can be waiting for some resources to available. Once the thread wait state is over, its state is changed to Runnable and it’s moved back to the runnable thread pool.
Once the thread finished executing, its state is changed to Dead and it’s considered to be not alive. A thread is in the terminated or dead state when its run() method exits.