Thread Life Cycle in Java
Thread Life Cycle in Java with Examples
In this article, I am going to discuss Thread Life Cycle in Java with examples. Please read our previous article where we discussed Thread Class in Java. The thread can exist in different states. Just because a thread’s start() method has been called, it doesn’t mean that the thread has access to the CPU and can start executing straight away. Several factors determine how it will process. So, at the end of this article, you will understand the life cycle of Thread in Java.
Thread Life Cycle in Java
A thread goes through various stages in its life cycle. According to Sun, there are only 4 states in the thread life cycle in java new, runnable, non-runnable, and terminated. There is no running state. But for a better understanding of the threads, we are explaining it in the 5 states. The life cycle of the thread in java is controlled by JVM.
- Newborn
- Runnable
- Running
- Blocked (Non-Runnable)
- Dead (Terminated)
Following are the stages of the life cycle –
New – A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. In simple words, a thread has been created, but it has not yet been started. A thread is started by calling its start() method.
Runnable – The thread is in the runnable state after the invocation of the start() method, but the thread scheduler has not selected it to be the running thread. A thread starts life in the Ready-to-run state by calling the start method and waiting for its turn. The thread scheduler decides which thread runs and for how long.
Running – When the thread starts executing, then the state is changed to a “running” state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
Dead – This is the state when the thread is terminated. The thread is in a running state and as soon as it is completed processing it is in a “dead state”. Once a thread is in this state, the thread cannot even run again.
Blocked (Non-runnable state):
This is the state when the thread is still alive but is currently not eligible to run. A thread that is blocked waiting for a monitor lock is in this state.
A running thread can transit to one of the non-runnable states depending on the situation. A thread remains in a non-runnable state until a special transition occurs. A thread doesn’t go directly to the running state from a non-runnable state but transits first to the Ready-to-run state.
The non-runnable states can be characterized as follows:
- Sleeping:- The thread sleeps for a specified amount of time.
- Blocked for I/O:- The thread waits for a blocking operation to complete.
- Blocked for Join completion: – The thread awaits completion of another thread.
- Waiting for notifications: – The thread awaits a notification from another thread.
- Blocked for lock acquisition: – The thread waits to acquire the lock of an object.
JVM executes a thread based on its priority and scheduling.
Example: Thread Life Cycle in Java
Here we are giving a simple example of the Thread life cycle. In this example, we will create a Java class where we will create a Thread, and then we will use some of its methods that represents its life cycle.
In this example, we have used the methods and indicated their purposes with the comment line. We have created two Thread subclasses named A1 and B. In both of the classes, we have to override the run() method and executed the statements. Then we created a ThreadLifeCycle.java class where we created instances of both classes and used the start() method to move the threads into the running state, yield() method to move the control to another thread, sleep() method to move into a blocked state. And after successful completion of the run() method the Thread is automatically moved into a Dead state.
A1.java
class A1 extends Thread < public void run () < System.out.println ("Thread A"); System.out.println ("i in Thread A "); for (int i = 1; i catch (InterruptedException e) < e.printStackTrace (); >> System.out.println ("Thread A Completed."); > >
B.java
class B extends Thread < public void run () < System.out.println ("Thread B"); System.out.println ("i in Thread B "); for (int i = 1; i System.out.println ("Thread B Completed."); > >
ThreadLifeCycleDemo.Java
public class ThreadLifeCycleDemo < public static void main (String[]args) < // life cycle of Thread // Thread's New State A1 threadA = new A1 (); B threadB = new B (); // Both the above threads are in runnable state // Running state of thread A & B threadA.start (); // Move control to another thread threadA.yield (); // Blocked State of thread B try < threadA.sleep (1000); >catch (InterruptedException e) < e.printStackTrace (); >threadB.start (); System.out.println ("Main Thread End"); > >
Output:
Thread Scheduler in Java:
- Preemptive scheduling: If a thread with a higher priority than the current running thread, then the current running thread is preempted(moves to the ready-to-run state) to let the higher priority thread execute.
- Time-sliced or Round-Robin scheduling: A running thread is allowed to execute for a fixed length of time, after which it moves to the Ready-to-run state to wait its turn to run again.
In the next article, I am going to discuss Thread Priority in Java with Examples. Here, in this article, I try to explain Thread Life Cycle in Java with examples. I hope you enjoy this Thread Life Cycle in Java with Examples article.
Java Thread Life Cycle and States
In Java, a Thread is a lightweight process that allows a program to operate more efficiently by running multiple threads in parallel. Internally, JVM creates a Thread and hands it over to the operating system for execution. The operating system then schedules, executes this thread and performs various state transitions between multiple threads.
During state transitions and life cycle, a Thread goes into various states depending on several factors such as thread priority, forcibly suspending a thread or waiting for the output of blocking operations.
1. Thread Life Cycle States
A Java thread can be in any of the following thread states during its life cycle:
- New
- Runnable (or Running)
- Blocked
- Waiting
- Timed Waiting
- Terminated
These are also called life cycle events of a thread. Let’s understand each state in more detail.
As soon as, you create new thread , it’s in NEW state. Thread remains in New state until the program starts the thread using its start() method. At this point, the thread is not alive.
Thread thread = new Thread(); System.out.println(thread.getState()); //NEW
Calling the thread.start() method puts the thread in RUNNABLE state. At this point, execution control is passed to OS thread scheduler to finish its execution. The thread scheduler decide from this point that this thread should be executed (also known as dispatching the thread) or should be put on hold to give chance to other runnable threads. Thread scheduling is platform dependent — the behavior of a multi-threaded program could vary across different Java implementations.
In most operating systems, each thread is given a small amount of processor time—called a quantum or timeslice—with which to perform its task. A task utilizing it’s quantum is said to be in RUNNING state. When its quantum expires, the thread returns to the RUNNABLE state, and the operating system assigns another thread to the processor.
The process that an operating system uses to determine which thread to dispatch is called thread scheduling and is dependent on thread priorities.
Thread thread = new Thread(); thread.start(); System.out.println(thread.getState()); //RUNNABLE
The operating system hide the RUNNABLE and RUNNING states from the Java Virtual Machine (JVM), which sees only the RUNNABLE state.
A RUNNABLE thread transitions to the BLOCKED state when it attempts to perform a task that cannot be completed immediately and it must temporarily wait until that task completes.
For example, when a thread issues an input/output request, the operating system blocks the thread from executing until that I/O request completes—at that point, the blocked thread transitions to the RUNNABLE state, so it can resume execution. A blocked thread cannot use a processor, even if one is available.
Usually program put a thread in WAIT state because something else needs to be done prior to what current thread is doing. A thread can be put in waiting state using
Once the thread wait state is over, its state is changed to RUNNABLE and it is moved back to thread pool.
A RUNNABLE thread can transition to the TIMED WAITING state if it provides an optional wait interval when it’s waiting for another thread to perform a task. You can put a java thread in TIMED WAITING state by calling using following methods:
- thread.sleep(long millis)
- wait(int timeout) or wait(int timeout, int nanos)
- thread.join(long millis)
Such a thread returns to the RUNNABLE state when it is notified by another thread or when the timed interval expires—whichever comes first. Timed waiting threads and waiting threads cannot use a processor, even if one is available.
A thread enters the TERMINATED state (sometimes called the dead state) when it successfully completes its task or otherwise terminated due to any error or even it was forcefully killed.
2. Deadlock and Starvation
Please remember that though JVM and OS thread scheduler do their best yet sometimes threads can cause starvation or deadlock.
A deadlock occurs when a waiting thread (let us call this thread1) cannot proceed because it is waiting (either directly or indirectly) for another thread (let us call this thread2) to proceed. And simultaneously thread2 cannot proceed because it is waiting (either directly or indirectly) for thread1 to proceed.
In this Java concurrency tutorial, we learned about the lifecycle of a Thread in Java, and how the state transitions happen between different states of the Thread.
Thread Life Cycle in Java — Thread States in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Understanding Thread Life Cycle in Java and Thread States are very important when you are working with Threads and programming for multithreaded environment. From our last tutorial, we can create a java thread class by implementing Runnable interface or by extending Thread class, but to start a java thread, we first have to create the Thread object and call it’s start() method to execute run() method as a thread.
Thread Life Cycle in Java
Below diagram shows different states of thread life cycle in java. We can create a thread in java and start it but how the thread states change from Runnable to Running to Blocked depends on the OS implementation of thread scheduler and java doesn’t have full control on that.
New
When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not alive and it’s a state internal to Java programming.
Runnable
When we call start() function on Thread object, it’s state is changed to Runnable. The control is given to Thread scheduler to finish it’s execution. Whether to run this thread instantly or keep it in runnable thread pool before running, depends on the OS implementation of thread scheduler.
Running
When thread is executing, it’s state is changed to Running. Thread scheduler picks one of the thread from the runnable thread pool and change it’s state to Running. Then CPU starts executing this thread. A thread can change state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run() method or waiting for some resources.
Blocked/Waiting
A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to available. For example producer consumer problem or waiter notifier implementation or IO resources, then it’s state is changed to Waiting. Once the thread wait state is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool.
Dead
Once the thread finished executing, it’s state is changed to Dead and it’s considered to be not alive. Above are the different states of thread. It’s good to know them and how thread changes it’s state. That’s all for thread life cycle in java.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us