Table of Content 7
Life Cycle of a Thread
When you create the thread, then Thread state is NEW.
When you start the thread, then will be placed in Ready To Run state and it will wait for CPU time.
Depending on the CPU Scheduling algorithm, thread will move from Ready to Run state to Running state or Running state to Ready to Run. When thread is in Running state then it will utilize CPU time, i.e. thread will execute its run() method tasks.
When you call sleep() method then the current running thread moves to Sleeping state. Thread will remain in sleep state for a specific time. Once the thread’s sleep will be over, it will move to Ready to Run state automatically. Sleep state is also called timed waiting state.
When you call wait method, then the currently thread move to wait state till you call method notify() or notifyAll() or when the specific time is over.
When a running thread is requesting unavailable resources then thread will move to block state. Thread in Block state will move to Ready to Run state when requested resources is available.
Blocked states may lead to deadlocks.
Consider the following case:
- In the above case, process P1 by holding the resources R1 requesting for resource R2 and P1 will complete its execution only when P1 gets resource R2.
- Similarly, process P2 by holding the resources R2 requesting for resource R1 and P2 will complete its execution only when it gets resource R1.
- So, here, both processes are requesting for unavailable resources. Both will be placed in Blocked state and both will not come out of Blocked state. This situation is called as Deadlock.
- Thread 1 demands resource-2(Hostage) but criminal’s friend owns the lock.
- Thread 2 demands resource-1(Criminal one) but cop owns the lock.
In this situation, no one will act first because each of them is waiting for others to release first. This is called Deadlock.