Thread Life Cycle in Java 

Thread-life-cycle-in-java-feature.jpg

The thread life cycle in Java describes various phases that a thread passes once it is created up to its termination. A thread is a small component of a program that enables multitasking or parallel execution, providing better performance and responsiveness. There are different states through which a thread goes in Java, which include New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. All these states denote a particular stage of the activity of a thread in a program. The thread life cycle can assist developers in dealing with threads in Java effectively, preventing resource contention, and creating effective multithreading programs. In this blog, let us explore the thread life cycle in Java, its different states, and a real-world example in detail.

Table of Contents:

What is Thread Life Cycle in Java?

In Java, the thread life cycle is the sequence of stages it goes through from creation to termination. In simple terms, it is the thread journey from beginning to end while performing some task. The thread in Java is a small work unit that runs autonomously to execute an operation that cannot block the main program. When a thread is created, it does not start its execution right away. It goes through multiple states/stages, such as New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. Understanding the thread life cycle in Java helps programmers control thread behavior, manage resources properly, and helps in avoiding errors like deadlocks or race conditions.

Become a Job-Ready Software Engineer
Master coding, system design, and real-world projects with expert mentors. Get certified and land your dream tech job
quiz-icon

Different States of a Thread Life Cycle in Java

The thread life cycle comprises several states that are used to describe the behavior of a thread during execution. 

Let us look at the main states in the thread life cycle:

  1. New State: When a thread is created using the thread class or the runnable interface, it has a state of New. In this state, the thread is not yet runnable because a start method was not called.
  2. Runnable State: When the start() method is called, the thread enters the RUNNABLE state. It is now eligible to run, but may need to wait for the CPU scheduler to allocate time for its execution. The thread in this state is active and may run at any moment when chosen by the scheduler.
  3. Blocked State: A thread goes into the blocked state when it is trying to access a resource or section of code that is currently being used by another thread. It stays blocked until access to the resource becomes available.
  4. Waiting State: A thread goes into the waiting state when it is waiting for another thread to do a specific task before it can continue execution. It will change states once another thread notifies the waiting thread to resume.
  5. Timed Waiting State: A thread is in the Timed waiting state when the thread is waiting for a specific time duration. This takes place when methods like sleep or wait are called. After the time passes, the thread automatically moves back to the runnable state.
  6. Terminated State: A thread reaches the terminated state once its task is finished or when it is stopped manually. After entering this state, the thread can not run again.

Flowchart of Thread Life Cycle

The thread life cycle in Java diagram is used to visually represent the movement of the thread from one state to another during its lifetime. Each transition depends on a specific action, like starting, waiting, sleeping, or finishing execution.

Below is a straightforward explanation of how the Java thread life cycle diagram flows:

Flowchart of Thread Life Cycle
  1. New State: The thread is created but hasn’t started yet.
  2. Runnable State: When start() is called, the thread becomes eligible to run. It may run immediately or wait for CPU time. Java does not split this into “runnable”.
  3. Blocked / Waiting / Timed Waiting: The thread is alive but not runnable because it’s waiting for a lock, waiting for another thread, or waiting for a fixed duration.
  4. Terminated State: The thread’s work is finished, and it cannot run again.

Java Example to Understand Thread Life Cycle States

To understand how the thread life cycle in Java works, let us look at the simple example that shows a thread moves through different states during execution.

class ThreadLifecycleExample extends Thread {
    public void run() {
        System.out.println("Thread is running");
        try {
            Thread.sleep(1000);  
            System.out.println("Thread is in Timed Waiting state");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread has finished execution");
    }
    public static void main(String[] args) {
        ThreadLifecycleExample t1 = new ThreadLifecycleExample();
        System.out.println("Thread state after creation: " + t1.getState());
        t1.start();
        System.out.println("Thread state after calling start(): " + t1.getState());
        try {
            Thread.sleep(500);
            System.out.println("Thread state while running: " + t1.getState());
            t1.join();
            System.out.println("Thread state after completion: " + t1.getState());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

image 146

Explanation: Here, the thread life cycle in Java example shows that the single thread moves across multiple states during its execution.

  • When a thread is created, it is in the new state.
  • After start(), it becomes RUNNABLE.
  • When sleep() is used, it goes into the TIMED_WAITING state.
  • Once execution finishes, it moves to the TERMINATED state.

How Java Transitions Between Thread States

Let’s now explore the transitions of thread states in Java

Step 1: Changing from New State to Runnable State 

When a thread is created, it will be in the New State. When you call the start() method, the thread will transition into the Runnable State and be ready to run. 

Step 2: Thread Execution Within the Runnable State

When a thread is in the RUNNABLE state, it may be either waiting to be scheduled or currently executing on the CPU.

Step 3: Changing from Runnable State to Blocked or Waiting State 

While the thread is in Runnable State, if the thread accesses a locked resource or waits for another thread to act, it will transition to Blocked or Waiting State. The thread will remain in the Blocked or Waiting State until the condition is fulfilled.

Step 4: Transitioning from Runnable to Timed Waiting

When a thread calls methods such as sleep(time) or wait(time), the thread enters the Timed Waiting state for the given time duration. Once the timer expires, the thread moves back automatically to the Runnable state. 

Step 5: Transition from Blocked or Waiting to Runnable

Once the resource is free or a notification is sent by another thread, the blocked or waiting thread will transition back to the Runnable state, where the scheduler can select the thread to execute.

Step 6: Transitioning from Runnable to Terminated

When the thread’s run() method completes execution, the thread reaches the Terminated state. A terminated thread will not be restarted.

Get 100% Hike!

Master Most in Demand Skills Now!

Common Thread Methods Used in Java

Method Description State Involved
start() Begins thread execution and internally calls the run() method. From NEW to RUNNABLE.
run() Contains the task that the thread performs. Executes while in RUNNABLE.
sleep(time) Suspends the thread for a given duration in milliseconds. Moves to TIMED_WAITING.
wait() Makes the thread wait until it is notified by another thread. Enters WAITING.
notify() Wakes a waiting thread so it can become runnable again. From WAITING to RUNNABLE.
join() Makes the current thread wait for another thread to finish execution. WAITING or TIMED_WAITING.
getState() Returns the current state of the thread. Any state.
isAlive() Checks if the thread has started and not yet terminated. RUNNABLE or TERMINATED.

Best Practices for Managing Threads in Java

  1. Avoid Blocking Code: Do not write long or blocking code inside the thread. Try to keep the task short so that the threads can complete quickly.
  2. Use Synchronization Carefully: Using synchronization helps in preventing multiple threads from accessing the shared data at the same time, but make sure not to overuse as it can reduce performance.
  3. Handle Exceptions Properly: Try to catch and handle the exceptions inside the run() method, which helps in preventing threads from stopping unexpectedly.
  4. Always Shutdown Threads: After finishing the work, do not forget to stop or shut down your threads to release system resources. 
  5. Avoid Busy Waiting: Use built-in methods like wait(), notify(), or join() to manage waiting threads efficiently.

Real-World Applications of Java Thread Life Cycle

The thread life cycle in Java is very useful in real-world projects where multiple tasks need to run at the same time. Let us explore the real-world applications of the thread life cycle:

  1. Web Servers: Web servers utilize multiple threads to cater to distinct client requests concurrently. Each incoming request is assigned a thread for processing, which increases speed and responsiveness.
  2. Banking Systems: In online banking systems, threads perform multiple operations concurrently, such as deposits, withdrawals, and transfers. This ensures fast execution of the operation without interfering with other users.
  3. Gaming Applications: Multithreading is commonly used in games to simultaneously manage tasks such as rendering graphics, playing sound, and receiving input from users, resulting in a fast, smooth, and good gaming experience.
  4. Chat Application: Threads are used in chat systems to handle sending and receiving messages.
Start Coding in Java for Free: No Experience Needed!
Begin writing actual Java code through interactive, beginner-friendly modules completely for free.
quiz-icon

Conclusion

In Java, the thread life cycle describes how a thread progresses from creation to runnable, pausing, and eventually ending when the program is executed. Each state in the life cycle, from New to Terminated, impacts how Java handles concurrent task execution. By understanding a thread’s life cycle in Java, developers can write faster and more efficient, and easier-to-control programs. Using the thread methods, synchronization, and proper management helps to prevent issues such as deadlocks and blocking on a resource.

Take your skills to the next level by enrolling in the Software Engineering Course today and gain hands-on experience. Also, prepare for job interviews with Software Engineering Interview Questions prepared by industry experts.

Thread Life Cycle in Java – FAQs

Q1. Can a terminated thread be restarted?

No, once a thread is terminated, it cannot be started again. You must create a new thread object.

Q2. What is the difference between Runnable and Running states?

Runnable means the thread is ready to run. Running means the thread is currently executing.

Q3. Why does a thread enter the Blocked state?

A thread enters the Blocked state when it tries to access a resource locked by another thread.

Q4. What does sleep() do in a thread?

The sleep method pauses the thread for a specific time, placing it in the Timed Waiting state

Q5. What happens when notify() is called?

When notify is used, one waiting thread becomes runnable and continues execution

About the Author

Technical Writer | Business Analyst

Yash Vardhan Gupta is an expert in data and business analysis, skilled at turning complex data into clear and actionable insights. He works with tools like Power BI, Tableau, SQL, and Markdown to develop effective documentation, including SRS and BRD. He helps teams interpret data, make informed decisions, and drive better business outcomes. He is also passionate about sharing his expertise in a simple and understandable way to help others learn and apply it effectively.

Full Stack Developer Course Banner