Threading: Understanding the Lifecycle and States of Threads

Threading: Understanding the Lifecycle and States of Threads

Everyone did multitasking in their life knowingly or unknowingly. Whether it's writing code while enjoying music or watching a video and downloading it at the same time. Here the multithreading works the same as in Java.

When two or more program run simultaneously or concurrently to maximum utilization of the CPU is called Multiprogramming or Multithreading. And each program is called Thread.

Now, let's discuss the thread's lifecycle.

  1. New - When a thread is instantiated it is in ‘New state’ until the start() method is called on the thread instance. In this state, the thread is not considered to be alive.

  2. Runnable - The thread enters into this state after the start method is called in the thread instance. The thread may enter into the ‘Runnable state’ from ‘Running state’ also. In this state, the thread is considered to be alive.

  3. Running - When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in ‘Running state’.

  4. Waiting/Blocked/Sleeping - In these states the thread is said to be alive but not Runnable. The thread switches to this state because of reasons like the wait method being called or the sleep method being called on the running thread or the thread might be blocked for some I/O resource.

  5. Dead - When the thread finishes its execution i.e. the run() method execution completes, it is said to be in a dead state. A dead state can’t be started again. If a start() method is invoked on a dead thread a runtime exception will occur.


Conclusion

Just like multitasking in real life, Multithreading allows you to accomplish multiple tasks simultaneously, leading to improved performance and responsiveness of your application.