Java Thread isInterrupted() Method

The Thread.isInterrupted() method in Java is used to check if the thread has been interrupted.

Table of Contents

  1. Introduction
  2. isInterrupted() Method Syntax
  3. How isInterrupted() Works
  4. Examples
    • Basic Usage
    • Using isInterrupted() with Sleep
    • Handling Interruption in a Loop
  5. Real-World Use Case
  6. Conclusion

Introduction

The Thread.isInterrupted() method is a member of the Thread class that checks if the thread has been interrupted. Unlike the Thread.interrupted() method, isInterrupted() does not clear the interrupted status of the thread. This method is useful for checking the interrupt status of a thread without altering it.

isInterrupted() Method Syntax

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

public boolean isInterrupted()

Returns:

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

How isInterrupted() Works

When a thread is interrupted, its interrupt status is set to true. The Thread.isInterrupted() method checks this status and returns true if the thread has been interrupted. It does not clear the interrupt status, so subsequent calls to isInterrupted() will continue to return true until the interrupt status is cleared.

Examples

Basic Usage

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

Example

public class IsInterruptedExample {
    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.

Using isInterrupted() with Sleep

You can use the isInterrupted() method to handle thread interruptions while the thread is sleeping.

Example

public class SleepIsInterruptedExample {
    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.");
                    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, exiting...

Handling Interruption in a Loop

You can use the isInterrupted() method in a loop to manage the execution flow based on the thread's interrupt status.

Example

public class LoopIsInterruptedExample {
    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.

Real-World Use Case

Graceful Shutdown

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

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) {
                    System.out.println("Interrupted during task execution.");
                    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...
Interrupted during task execution.
Cleaning up resources...
Thread is exiting.

Conclusion

The Thread.isInterrupted() method in Java provides a way to check if a thread has been interrupted without clearing the 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 isInterrupted() method offers used for controlling thread behavior in Java.

Comments