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

Let’s talk about multithreading before we get into our topic thread in Java and thread life cycle in Java. Multithreading expands the concept of completing many tasks at the same time, which is also applicable in real life. For example, in the bus ticket reservation system, numerous customers can access the server at the same time to buy 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?

In terms of the operating system, a thread is the smallest processing unit. A thread is a separate execution path in a code.
A thread in Java is a separate flow of execution within a Java program. A Java program can contain multiple threads, which can run concurrently and independently of each other. Threads can be used to perform tasks such as background processing, managing multiple user interactions, or 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 is important to note that the exact sequence of events in the life cycle of thread in java can vary and that multiple threads can exist in the same state at the same time.

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.

Summary

  • Thread in Java enable multiprogramming, which allows a program or process to run more than one instruction at a time.
  • A thread in Java also allows a complex or huge task to run in the background without interfering with the main program.
  • In Java, the Thread class and the Runnable interface allow us to construct and control threads.
  • A thread in java goes through five states from creation to termination: new state, active state, waiting or blocked state, timed waiting for the state, and terminated state.
  • By implementing the Runnable interface, we can also create a thread in Java. To create a new thread, we send the reference to the Runnable implemented class to the Thread object’s constructor.
  • Several constructors and methods for various purposes have been declared in the java.lang.Thread class.

Frequently Asked Questions (FAQs)

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

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

Question 2 – What is the distinction between a process and a thread in Java?
Answer – 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.

Question 3 – What is the difference between start() and run() methods in Java?
Answer – 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.

Question 4 – What is the difference between sleep() and wait() methods in Java?
Answer – The sleep() method is used to cause the current thread to temporarily halt execution for a specified time, while the wait() method is used to cause a thread to wait until another thread notifies it.

Question 5 – What is the difference between yield() and join() methods in Java?
Answer – The yield() method is used to cause the current thread to voluntarily give up its execution time to other threads, whereas a join() method is used to make a thread wait while another thread finishes its execution.

Leave a Reply

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