Java Thread interrupt()

In this guide, you will learn about the Thread interrupt() method in Java programming and how to use it with an example.

1. Thread interrupt() Method Overview

Definition:

The Thread.interrupt() method is used to interrupt a thread's execution. If the target thread is currently in a blocking operation (like Thread.sleep(), wait(), or I/O operations), it will receive an InterruptedException.

Syntax:

public void interrupt()

Parameters:

- None.

Key Points:

- Interrupting a thread doesn't necessarily stop its execution but merely sets its interrupt status.

- If a thread is in a blocking operation that supports interruption, it will throw InterruptedException.

- If a thread is not in a blocking state, calling interrupt() will just set the interrupt status, which can be later checked using the Thread.isInterrupted() method.

- It provides a gentle way to tell a thread to stop what it's doing and check if it should terminate (as opposed to forcefully stopping a thread).

2. Thread interrupt() Method Example

public class ThreadInterruptExample {
    public static void main(String[] args) {
        Thread sleepingThread = new Thread(() -> {
            try {
                // This thread will sleep for 10 seconds
                System.out.println("Going to sleep...");
                Thread.sleep(10000);
                System.out.println("Woke up normally.");
            } catch (InterruptedException e) {
                System.out.println("Thread was interrupted during sleep.");
            }
        });

        sleepingThread.start();

        // Give the thread a moment to start sleeping
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ignored) {}

        // Now, interrupt the sleeping thread
        sleepingThread.interrupt();
    }
}

Output:

Going to sleep...
Thread was interrupted during sleep.

Explanation:

In the given example, we create a sleepingThread that tries to sleep for 10 seconds. 

After giving it 2 seconds to start sleeping, we interrupt the sleepingThread

Since sleep() is a blocking method that supports interruption, it throws an InterruptedException as soon as the interrupt() method is called on the thread. This is why the output shows "Thread was interrupted during sleep." rather than "Woke up normally.".

Comments