When you need to program in a multithreaded environment using Java threads, it is important to understand the thread cycles and the state of the threads in Java. By implementing the Runnale interface or inheriting the thread class, we can create a thread, in order to start a thread, we need to create a thread object and invoke its start () method to execute the run () method in a thread manner.
thread life cycle in Java
The following figure shows the different states of a thread in Java, we can create a Java thread and invoke the start () method to start it, but how the state of the threads changes from running to blocked, which relies on the thread scheduling algorithm implemented with the operating system, Java does not have enough control over this.
New
When we create a new thread object, we need to use the time new operator, at which point the state of the thread is new. At this point, the thread is not scheduled, it is just an internal state of the Java language.
Runnable
When we call the start () function of the thread object, its state changes to runnable. Control is given to the thread scheduler to complete its execution. Whether to run this thread immediately or to keep it in a running thread pool before running depends on the implementation of the thread scheduler.
Running
When the thread is executing, the state changes to running. The thread scheduler chooses a thread from the pool of running threads, changes its state to running, and then the CPU starts to execute the thread. A thread can change the running process state to runnable,dead or blocked. In that state, the thread executes the logic of the Run () method.
Blocked/waiting
a thread can wait for the execution of another thread through the join () method, or wait for some resources to be available. For example, a producer consumer problem or IO resource, at which point the state of the thread becomes waiting. After the thread waits for the state to end, the state becomes runnable and moves back to the running thread pool.
Dead
Once the thread has finished executing, its state becomes dead.
Finish
Java Thread life cycle