Java Thread interrupt Example

Introduction

The interrupt method in Java is used to interrupt a thread that is currently running. This method sets the thread's interrupt status to true. If the thread is in a blocked state (such as waiting, sleeping, or blocked on I/O), an InterruptedException is thrown. The interrupted thread can then handle the interruption and take appropriate action.

Table of Contents

  1. How to Interrupt a Thread
  2. Checking the Interrupt Status
  3. Handling InterruptedException
  4. Example: Interrupting a Thread
  5. Example: Handling Interruption in a Sleeping Thread
  6. Conclusion

1. How to Interrupt a Thread

To interrupt a thread, you can call the interrupt method on the thread instance.

Syntax:

public void interrupt()

2. Checking the Interrupt Status

You can check the interrupt status of a thread using the isInterrupted method or the static Thread.interrupted method.

Syntax:

public boolean isInterrupted() // Checks the interrupt status without clearing it

public static boolean interrupted() // Checks the interrupt status and clears it

3. Handling InterruptedException

When a thread is interrupted while it is in a blocked state (e.g., sleeping or waiting), an InterruptedException is thrown. You need to handle this exception using a try-catch block.

4. Example: Interrupting a Thread

Let's create an example to demonstrate how to interrupt a thread and check its interrupt status.

Example:

class MyThread extends Thread {
    public MyThread(String name) {
        super(name); // Set the name of the thread
    }

    @Override
    public void run() {
        while (!isInterrupted()) {
            System.out.println(Thread.currentThread().getName() + " is running.");
            try {
                Thread.sleep(1000); // Sleep for 1 second
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " was interrupted during sleep.");
                interrupt(); // Re-interrupt the thread
            }
        }
        System.out.println(Thread.currentThread().getName() + " has finished.");
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread-1");

        thread1.start(); // Start thread1

        try {
            Thread.sleep(3000); // Main thread sleeps for 3 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        thread1.interrupt(); // Interrupt thread1
    }
}

Output:

Thread-1 is running.
Thread-1 is running.
Thread-1 is running.
Thread-1 was interrupted during sleep.
Thread-1 has finished.

Explanation:

  • The MyThread class extends the Thread class and sets the name of the thread.
  • The run method checks if the thread has been interrupted using the isInterrupted method and prints a message if it is running.
  • If the thread is interrupted during sleep, an InterruptedException is caught, and the thread is re-interrupted by calling interrupt again.
  • In the main method, a MyThread object is created and started.
  • The main thread sleeps for 3 seconds and then interrupts thread1.

5. Example: Handling Interruption in a Sleeping Thread

This example demonstrates handling an interruption in a thread that is sleeping.

Example:

class MyThread extends Thread {
    public MyThread(String name) {
        super(name); // Set the name of the thread
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            if (isInterrupted()) {
                System.out.println(Thread.currentThread().getName() + " was interrupted.");
                break;
            }
            System.out.println(Thread.currentThread().getName() + " is running. Iteration: " + i);
            try {
                Thread.sleep(1000); // Sleep for 1 second
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " was interrupted during sleep.");
                break;
            }
        }
        System.out.println(Thread.currentThread().getName() + " has finished.");
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread-1");

        thread1.start(); // Start thread1

        try {
            Thread.sleep(3000); // Main thread sleeps for 3 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        thread1.interrupt(); // Interrupt thread1
    }
}

Output:

Thread-1 is running. Iteration: 0
Thread-1 is running. Iteration: 1
Thread-1 is running. Iteration: 2
Thread-1 was interrupted during sleep.
Thread-1 has finished.

Explanation:

  • The MyThread class extends the Thread class and sets the name of the thread.
  • The run method checks if the thread has been interrupted using the isInterrupted method before each iteration and prints a message if it is running.
  • If the thread is interrupted during sleep, an InterruptedException is caught, and the thread prints a message and breaks out of the loop.
  • In the main method, a MyThread object is created and started.
  • The main thread sleeps for 3 seconds and then interrupts thread1.

6. Conclusion

The interrupt method in Java is used for controlling the execution of threads. By using the interrupt, isInterrupted, and interrupted methods, you can handle thread interruptions gracefully. Properly handling InterruptedException ensures that your threads can respond to interruptions in a controlled manner, allowing your application to behave as expected under various conditions.

Happy coding!

Comments