Life Cycle of Thread in Java with Diagram
Thread Life Cycle:
A thread life cycle is always in one of these five states. It can move from one state to another state. In Java, the life cycle of a thread has five states.
-
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Life Cycle of Thread in Java:
Newborn State:
When we want to create a thread object, the thread is born then it is said to be Newborn State. At this State, we can do this by using the start() method.
Runnable State:
It means that the thread is ready for execution and it is waiting for the availability of the processor. If all threads have equal priority, then they are given time slots for execution FCFS manner (First Come First Serve).
Then the thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to threads that are known as Time-Slicing. At this State, we can do by using yield() method.
Running State:
It means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own. When a running thread may relinquish its control, then the following situations occur:
i. It is suspend using suspend() method. A suspended thread can be revived by using resume() method.
ii. It has been made to sleep. So, we can put to sleep a thread for a specified time period by using the sleep(time) method, where time is in milliseconds. It means that the thread is out of the queue during this time period.
iii. It has been told to wait until some event occurs. We can do by using wait() method. Then the thread can schedule to run again using notify() method.
Blocked State:
A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping or waiting to satisfy certain requirements. A blocked thread is “not runnable” but not dead.
Dead State:
A running thread ends its life when it has completed executing its run() method. It is a natural death. We can kill the thread by using the stop() method.