Now that we are already through the basics on Multithreading in our previous article, lets know about the thread life cycle, which is yet another trending topic for the interviews.
So basically, what we understood till now, is that, for a particular process to complete, we invoke a primary thread, which in turn invokes one or more threads to efficiently serve the purpose, working independently while being the part of the same process. I hope I am clear on this! The point from the process start to the end, involves several threads being created and destroyed. Now, in between the creation of the thread to it’s destruction/termination involves several other life cycle states, which we will have a small overview on.
There are five states in the life cycle of a thread:
Refer the diagram below to understand the thread states better.
- New – When a new thread is created using the new operator, the thread is said to be in a New state.
- Runnable – The moment the start() method is invoked on the newly created thread object, the thread state changes to Runnable, which means that the thread is now ready to run. A thread in this state first enters the Runnable thread pool and gets picked up from there by the OS thread scheduler for being executed.
- Running – Once the thread scheduler picks up a particular thread from the Runnable thread pool for execution, the thread enters the Running state. A thread in a Running state can switch back to Runnable, Wait or Dead state, depending on the time slicing, resource availability or if the task assigned to that particular thread has completed.
- Blocked/Waiting – A thread can enters this state if the resource that it relies on, isn’t available at the moment or is being occupied by another thread. Thread synchronization is the concept involved, which we will be learning very soon. Once the wait state is over, the thread again enters the Runnable thread pool and waits for it’s chance to be chosen by the scheduler for execution.
- Dead/Terminated – A thread after finishing its designated task (when the run() method exits), enters into this state.