Life Cycle of Thread in Java
Updated on Dec 30, 2024 | 10 min read | 6.1k views
Share:
For working professionals
For fresh graduates
More
Updated on Dec 30, 2024 | 10 min read | 6.1k views
Share:
Table of Contents
A thread in Java facilitates the performance of multiple activities inside a single process. It is regarded as a lightweight process. A thread can also be defined as a sequence of executed statements. Every thread in Java has its own stack, program counter and local variables. Java threads may also be a nested series of method calls. The memory, per-process state and files are shared by threads.
To illustrate this concept further, let’s look at thread life cycle example program in Java:
public class ThreadLifeCycle {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
System.out.println("Thread in New State: " + t1.getState());
t1.start(); // start the thread, entering Runnable state
System.out.println("Thread in Runnable State: " + t1.getState());
// wait for the thread to transition to Running state or interrupt it
while (t1.isAlive()) {
System.out.println("Thread in Running State: "+ t1.getState());
try {
Thread.sleep(200); // wait for the thread to finish or be blocked
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(“Thread in Dead/Terminated State: ” + t1.getState()); //at this point, the thread is dead and cannot be restarted again
}
static class MyRunnable implements Runnable {
public void run() {
Some task here… //the thread is now executing its instructions in the Running state
}
}
}
By understanding the life cycle of thread in Java, developers can write programs that make use of the multithreading capabilities of the JVM. This will lead to an efficient and optimized code base and better application performance.
If you’re asked to write a Java program to implement thread life cycle , you can use the example program above as a reference to get started. Additionally, make sure to read more about thread life cycle in Java and understand all of its components and states before attempting to write your program. With practice and guidance from experienced mentors, you should be able to create an effective implementation of thread life cycle in Java.
Uses of threads in Java:
There exist two execution paths when a thread is called. One of the two paths is used for thread execution and the other one will trail the statement succeeding the thread invocation. Each thread in Java has a separate memory space and stack.
The risk factors encountered while using threads in Java codes are as follows.
At any instant of program execution, the threads in Java exist in any one of the below-mentioned states.
New thread:
The newly created thread is in the state ‘New’. It is not progressed to run at this state. The execution of the code of a thread in the new state is yet to take place. It is yet to run.
Runnable state:
The threads in the runnable state are ready to run. A thread in this state maybe ready to run at any time instant or may already be running. The thread scheduler hones the responsibility of allocating time for the thread to run. Each individual thread is allocated a specific time in a multi-threaded program. Each individual thread runs for a small duration and then encounters a pause. The CPU is then relinquished to another thread to provide a chance for the other threads to run. At this point, all the ready to run threads that are waiting for the CPU and the threads that are running currently lie in a runnable state.
Check out our free technology courses to get an edge over the competition.
Waiting /Blocked state:
A thread is in any one of the below-mentioned states when it is temporarily not operating.
A thread waiting for the completion of I/O is in a blocked state. The thread scheduler’s function is to schedule the execution of a blocked or waiting thread by reactivating it. Any thread in this state is not allowed for the further continuation of execution till it is transformed to a runnable state. The threads in the block or waiting state do not use any CPU cycle.
A thread is forced to be blocked when it attempts to access a code’s protected section that is protected by some other thread at present. The scheduler transforms one of the threads waiting for a protected section into a runnable state when the section is unlocked for all the threads. On the other hand, a thread exists in a waiting state while it waits for the other thread on a particular condition. The threads in the waiting state are pushed to a runnable state once the condition specified for waiting is satisfied. If a thread running at present is moved to a waiting / blocked state, the thread scheduler schedules another thread from the runnable sequence to run.
Timed Waiting:
When a method is invoked with a time out argument, the thread exists in a timed waiting state. A thread continues to lie in this state till the completion of specified timeout or until the reception of a notification. For example, a thread is shifted to a timed waiting state if it invokes conditional wait or sleep.
Terminated state:
The termination of threads takes place because of any one of the following reasons.
A thread in a terminated state does not consume any CPU cycles.
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
To accomplish the current state of a thread in Java, we use the method Thread.getState(). Java also offers the java.lang.Thread.State class in which the ENUM constants for a thread’s state is defined. The details are summarized in the table below.
Constant Type | Declaration | Description |
New | public static final Thread.State NEW | It is the thread state of the thread that is just created and yet to start its execution. |
Runnable | public static final Thread.State RUNNABLE | It describes the state of a thread that is already running or a thread that is in ready to run state. The same thread can be in a runnable state for the Java Virtual machine and waiting state for other operating system resources such as a processor. |
Blocked | public static final Thread.State BLOCKED | It describes the state of a thread that is blocked waiting for the monitor lock. It remains in the same state until the monitor block enters a synchronized method/block or re-enters the synchronized method after invoking the Object.wait(). |
Waiting | public static final Thread.State WAITING | It describes the state of a thread that is waiting due to the invoking of one of the following methods.
The waiting state may be because of the completion of a particular task by another thread. |
Timed waiting | public static final Thread.State TIMED_WAITING | It is a state of the thread that waits for a specified time. The invocation of any of the following methods results in a timed waiting state of a thread with an assigned positive waiting time.
|
Terminated | public static final Thread.State TERMINATED | It is the state of a thread that has completed executing its constituent code statements. |
The thread rests in a NEW state when it is just created. When the .start() method is invoked on a thread, it is moved to a Runnable state by the thread scheduler. When the join() method is invoked on a thread instance, the thread that is executing the code statement currently will wait for this thread to terminate. So, prior to the printing of the final statement on the console, the join() function is invoked on thread 2 by the program and keeps the thread1 on wait till the thread2 completes its execution and moves to the Terminated State. Since thread1 is waiting for the completion of thread2’s execution, it is put in the WAITING state.
The use of threads in Java programs has the following benefits.
There are several drawbacks of using threads in Java programs. Some of them are listed below.
The life cycle of a thread in Java is an essential part of the process of programming multi-threaded applications. It helps us to understand the various states that a thread can transition between and how these transitions occur throughout program execution. Furthermore, understanding the merits and limitations of using threads in a program can help us decide whether or not they are the right choice for our specific application. Ultimately, knowledge about thread life cycles provides us with an invaluable resource when writing multi-threaded applications in Java. With this information at hand, we have a better chance of transforming our code into efficient and robust programs.
If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources