Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Thread in Java and Its Life Cycle

Last Updated on October 16, 2023 by Ankit Kochar

Before delving into the topic of threads in Java and the life cycle of threads in Java, let’s explore the concept of multithreading. Multithreading extends the idea of concurrently performing multiple tasks, a concept that mirrors real-life scenarios. For instance, in a bus ticket reservation system, numerous customers can simultaneously access the server to purchase their tickets.
We’ll talk about threads in Java and how they go through several stages during their lifecycle and can only be in one of six states at any given moment.

What is Thread in Java?

Regarding the operating system, a thread represents the smallest processing unit and serves as an autonomous execution path within a code.
In the context of Java, a thread signifies an individual execution sequence within a Java program. Java programs can encompass multiple threads, each capable of concurrent and autonomous operation. Threads find application in various tasks, including background processing, handling multiple user interactions, and implementing animations.

By using threads, a Java program can perform multiple tasks simultaneously, increasing its overall responsiveness and performance.

Different Ways to Build a Thread in Java

There are two main ways to create a thread in Java:

  1. Extending the java.lang.Thread class: The java.lang.Thread class provides a basic implementation of the java.lang.Runnable interface and allows you to create a new thread by extending the Thread class and overriding its run() method. The run() method defines the task that the thread will perform when it starts. To start the thread, you need to call the start() method.

    class MyThread extends Thread {
    public void run() {
    // Task to be performed by the thread
    }
    }

    public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.start();
    }

  2. Implementing the java.lang.Runnable interface: The java.lang.Runnable interface is a functional interface that defines a single method, run(), which contains the code that the thread will execute. To create a new thread, you need to create an instance of java.lang.Thread and pass the Runnable instance to its constructor. To start the thread, you need to call the start() method on the java.lang.Thread instance.

    class MyRunnable implements Runnable {
    public void run() {
    // Task to be performed by the thread
    }
    }

    public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    Thread myThread = new Thread(myRunnable);
    myThread.start();
    }

Both methods are valid ways of creating a new thread in Java, and the choice between them depends on the specific requirements of your program.

What are Thread Methods in Java?

The java.lang.Thread class provides several methods for creating and managing threads in Java. Some of the commonly used methods include:

  1. start(): Starts the execution of the thread. This method calls the run() method in a new thread of execution.
  2. run(): Contains the code that the thread will execute when it starts.
  3. sleep(long millis): Causes the current thread to pause execution for the specified amount of time (in milliseconds).
  4. join(): Causes the current thread to wait for the completion of the specified thread.
  5. yield(): Causes the current thread to temporarily pause execution and allow other threads to run.
  6. interrupt(): Interrupts the current thread.
  7. getName(): Returns the name of the thread.
  8. setName(String name): Changes the name of the thread.
  9. isAlive(): Returns a Boolean indicating whether the thread is still running.
  10. setPriority(int priority): Changes the priority of the thread.

These are just a few of the methods available in the java.lang.Thread class, and the specific methods used in your program will depend on your specific requirements.

Thread Life Cycle in Java

The thread life cycle in Java consists of the following stages:

  • New
  • Active
  • Blocked/Waiting
  • Timed Waiting
  • Terminated

It’s worth emphasizing that the precise sequence of events within the thread life cycle in Java can vary, and multiple threads can coexist in the same state simultaneously.

Given below is brief overview of each states of Thread Life Cycle in Java

1. New State:

The "New" state in the life cycle of thread in Java refers to the state where a thread has been created but has not yet started.

In this state, a thread object has been instantiated, but the start() method has not yet been called on it, so the thread has not begun executing. The thread remains in the "New" state until the start() method is called, at which point it transitions to the "Runnable" state and is ready to be executed by the Java virtual machine.

The "New" state is the initial state of a thread in Java, and is an important part of the life cycle of thread in java, as it represents the creation of a new thread and the beginning of its journey to becoming a running thread.

2. Active State:

When a thread calls the start() method, it transitions from the new to the active state. The active state contains two states: one that is runnable and one that is running.

(i) Runnable:
The "Runnable" state in the life cycle of thread in Java refers to the state where a thread is ready to run, but may be waiting for resources to become available.

In this state, a thread has been created and started, but has not yet begun execution. The thread is waiting for the Java virtual machine to execute it. The thread remains in this state until the JVM schedules it to run and moves it to the "Running" state.

A thread can enter the "Runnable" state from the "New" state after it has been created and started, or from the "Blocked" state after it has finished waiting for a resource or synchronization lock.

The "Runnable" state is an important part of the life cycle of thread in Java, as it is the state where a thread is ready to execute and contribute to the overall processing of the program.

(ii) Running:
The "Running" state in the life cycle of thread in Java refers to the state where a thread is currently executing.

In this state, a thread has been scheduled by the Java virtual machine to run and is actively executing its code. The thread remains in the "Running" state until it completes its execution, is blocked waiting for a resource or synchronization lock, or is voluntarily paused using methods such as sleep() or yield().

A thread can enter the "Running" state from the "Runnable" state, when the JVM schedules it to run, or from the "Blocked" state, after it has acquired the necessary resources or synchronization locks.

The "Running" state is an important part of the life cycle of thread in Java, as it is the state where a thread is actively executing its code and contributing to the overall processing of the program.

3. Block or Waiting State:

The "Blocked/Waiting" state in the life cycle of thread in Java refers to the state where a thread is waiting for a resource or synchronization lock.

In this state, a thread is unable to proceed with its execution until it acquires the necessary resources or synchronization locks. The thread continues in the "Blocked/Waiting" state until the resource becomes available or the lock is released, at which time it changes to the "Runnable" state and is ready for execution by the Java virtual machine.

Examples of situations that can cause a thread to enter the "Blocked/Waiting" state include waiting for input from a user, waiting for data to be loaded from a database, and waiting for access to a synchronized section of code.

The "Blocked/Waiting" state is an important part of the life cycle of thread in Java, as it represents a temporary pause in the execution of a thread while it waits for resources to become available.

4. Timed Waiting State:

Waiting can sometimes lead to starvation. For example, suppose a thread (let’s call it P) has entered a critical section of code and refuses to exit. In such a case, another thread (let’s call it B) is forced to wait indefinitely, resulting in starvation. Thread B is placed in a timed waiting state to avoid this issue. Thus, thread is in the waiting state for a fixed amount of time and not indefinitely. When we call the sleep() method on a specified thread, we are using timed waiting. The sleep() function places the thread in timed wait mode. When the timer expires, the thread wakes up and resumes execution from where it left off.

5. Termination State:

The “Termination” state in the life cycle of thread in Java refers to the state where a thread has completed its execution.

In this state, a thread has run to completion and has exited its run() method. The thread remains in the “Termination” state until its resources are cleaned up by the Java virtual machine. After that, the thread is considered to be terminated and no longer exists.

A thread can enter the “Termination” state from the "Running" state after it has completed its execution, or from the "Blocked/Waiting" state after it has been interrupted or has timed out while waiting for a resource.

The "Termination" state is the final state in the life cycle of thread in Java, and represents the end of a thread’s journey as a running piece of code.

Conclusion
In conclusion, understanding threads and their life cycle in Java is crucial for developing concurrent and responsive applications. Threads allow Java programs to execute multiple tasks concurrently, enhancing efficiency and responsiveness. The thread life cycle encompasses various states, and the exact progression can vary, depending on factors such as system resources and scheduling. By mastering thread management in Java, developers can create robust and efficient applications that can handle a wide range of tasks concurrently.

Frequently Asked Questions (FAQs) related to Thread in Java and its Life Cycle

Below are some important questions and answers on Thread in Java and Thread life cycle in Java:

1. What are the different states in the life cycle of a thread in Java?
The states in the life cycle of thread in Java are: New, Active, Blocked/Waiting, Timid Waiting and Termination.

2. What is the distinction between a process and a thread in Java?
A process is a self-contained execution environment that has its own memory space and system resources, while a thread is a lightweight unit of execution within a process that shares the process’s memory space and system resources.

3. What is the difference between start() and run() methods in Java?
The start() method creates a new thread and starts its execution, while the run() method is the entry point for a thread and contains the code that will be executed.

4. What is the significance of thread synchronization in Java?
Thread synchronization is crucial for ensuring that multiple threads can access shared resources safely and prevent data corruption or race conditions.

5. How can I create and manage threads in Java?
Threads in Java can be created by extending the Thread class or implementing the Runnable interface. They can be managed using methods like start(), join(), and synchronized blocks.

6. What is the purpose of the synchronized keyword in Java threads?
The synchronized keyword is used to ensure that only one thread can access a synchronized block or method at a time, preventing data inconsistencies and conflicts in multi-threaded environments.

7. Can multiple threads run concurrently in a Java program?
Yes, multiple threads can run concurrently in a Java program, allowing for parallel execution of tasks.

8. What is the Java Thread Priority and how does it affect execution?
Java threads can have priorities ranging from 1 to 10, with higher numbers indicating higher priority. Priority affects the order in which threads are scheduled by the JVM, but it’s not guaranteed to control precise execution order.

Leave a Reply

Your email address will not be published. Required fields are marked *