Java Thread interrupted() Method

The Thread.interrupted() method in Java is used to check if the current thread has been interrupted and, if so, clear the interrupted status of the thread.

Table of Contents

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

Introduction

The Thread.interrupted() method is a static method in the Thread class that checks the interrupt status of the current thread. If the thread has been interrupted, the method returns true and clears the interrupted status. This is useful for handling interrupts and managing the execution flow of threads.

interrupted() Method Syntax

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

public static boolean interrupted()

Returns:

  • true if the current thread has been interrupted; false otherwise.

How Thread Interruption Works

When a thread is interrupted, its interrupt status is set to true. The Thread.interrupted() method checks this status and, if it is true, clears the status and returns true. This allows a thread to handle an interrupt and then continue its execution with a reset interrupt status.

Examples

Basic Usage

To demonstrate the basic usage of interrupted(), we will create a thread, interrupt it, and check its interrupt status.

Example

public class InterruptedExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.interrupted()) {
                    System.out.println("Thread was interrupted.");
                    break;
                }
                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
                }
            }
        });

        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.

Handling InterruptedException

When a thread is interrupted while it is blocked, it receives an InterruptedException. You can use the interrupted() method to handle this and continue execution.

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.");
                if (Thread.interrupted()) {
                    System.out.println("Interrupt status cleared.");
                }
            }
        });

        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.
Interrupt status cleared.

Loop with interrupted()

You can use the interrupted() method in a loop to handle interruptions and manage the execution flow.

Example

public class LoopWithInterruptedExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.interrupted()) {
                System.out.println("Thread is running...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    System.out.println("Thread was interrupted during sleep.");
                    break;
                }
            }
            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.

Real-World Use Case

Graceful Shutdown

In real-world scenarios, the interrupted() method can be used for implementing a graceful shutdown of threads. This allows threads to finish their current tasks and clean up resources before terminating.

Example

public class GracefulShutdownExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            while (!Thread.interrupted()) {
                System.out.println("Performing task...");
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    System.out.println("Interrupted during task execution.");
                    break;
                }
            }
            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...
Interrupted during task execution.
Cleaning up resources...
Thread is exiting.

Conclusion

The Thread.interrupted() method in Java provides a way to check if the current thread has been interrupted and clear its interrupt status. By understanding how to use this method, you can manage the execution flow of threads more effectively in your Java applications. Whether you are handling interruptions, managing thread lifecycle, or implementing graceful shutdowns, the interrupted() method offers used for controlling thread behavior in Java.

Comments