Java Thread interrupt() Method

The Thread.interrupt() method in Java is used to interrupt a thread.

Table of Contents

  1. Introduction
  2. interrupt() Method Syntax
  3. How Thread Interruption Works
  4. Examples
    • Basic Usage
    • Handling InterruptedException
    • Checking Interrupt Status
  5. Real-World Use Case
  6. Conclusion

Introduction

The Thread.interrupt() method is used to interrupt a thread that is currently executing. Interrupting a thread sets its interrupt status, which can be checked using the isInterrupted() method or the static interrupted() method. Interruption is commonly used to signal a thread to stop its execution or to handle cleanup tasks.

interrupt() Method Syntax

The syntax for the interrupt() method is as follows:

public void interrupt()

Returns:

  • This method does not return a value.

Throws:

  • SecurityException if the current thread cannot modify the target thread.

How Thread Interruption Works

When a thread is interrupted, its interrupt status is set to true. If the thread is blocked in a call to wait(), sleep(), or join(), it will receive an InterruptedException, and its interrupt status will be cleared. Otherwise, the thread's interrupt status remains set.

Examples

Basic Usage

To demonstrate the basic usage of interrupt(), we will create a thread and interrupt it while it is running.

Example

public class InterruptExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread is running...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    System.out.println("Thread was interrupted during sleep.");
                    Thread.currentThread().interrupt(); // Preserve the interrupt status
                }
            }
            System.out.println("Thread is exiting.");
        });

        thread.start();

        try {
            Thread.sleep(3000); // Let the thread run for a while
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        thread.interrupt();
    }
}

Output:

Thread is running...
Thread is running...
Thread is running...
Thread was interrupted during sleep.
Thread is exiting.

Handling InterruptedException

When a thread is interrupted while it is blocked, it receives an InterruptedException. You can handle this exception to perform cleanup tasks or stop the thread gracefully.

Example

public class HandleInterruptedExceptionExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                while (true) {
                    System.out.println("Thread is running...");
                    Thread.sleep(1000); // Simulate work
                }
            } catch (InterruptedException e) {
                System.out.println("Thread was interrupted.");
            }
            System.out.println("Thread is exiting.");
        });

        thread.start();

        try {
            Thread.sleep(3000); // Let the thread run for a while
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        thread.interrupt();
    }
}

Output:

Thread is running...
Thread is running...
Thread is running...
Thread was interrupted.
Thread is exiting.

Checking Interrupt Status

You can check a thread's interrupt status using the isInterrupted() method or the static interrupted() method.

Example

public class CheckInterruptStatusExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Thread was interrupted, exiting...");
                    break;
                }
                System.out.println("Thread is running...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    System.out.println("Thread was interrupted during sleep.");
                    break;
                }
            }
        });

        thread.start();

        try {
            Thread.sleep(3000); // Let the thread run for a while
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        thread.interrupt();
    }
}

Output:

Thread is running...
Thread is running...
Thread is running...
Thread was interrupted during sleep.
Thread was interrupted, exiting...

Real-World Use Case

Stopping Threads Gracefully

In a real-world scenario, you might want to stop a long-running thread gracefully, ensuring that it completes any necessary cleanup tasks.

Example

public class GracefulShutdownExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Performing task...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // Preserve the interrupt status
                }
            }
            System.out.println("Cleaning up resources...");
            System.out.println("Thread is exiting.");
        };

        Thread workerThread = new Thread(task);
        workerThread.start();

        try {
            Thread.sleep(5000); // Let the thread run for a while
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        workerThread.interrupt();
    }
}

Output:

Performing task...
Performing task...
Performing task...
Performing task...
Cleaning up resources...
Thread is exiting.

Conclusion

The Thread.interrupt() method in Java provides a way to interrupt a thread and signal it to stop its execution or handle cleanup tasks. By understanding how to use this method, you can manage the lifecycle of threads more effectively in your Java applications. Whether you are handling long-running tasks, managing resources, or ensuring graceful shutdowns, the interrupt() method offers used for controlling thread execution in Java.

Comments