Interrupting Threads in Java

Interrupting a thread in Java is a way to signal a thread that it should stop what it is doing and perform some other action, usually to terminate gracefully. The thread can check for an interrupt status and respond appropriately.

Key Points on Thread Interruption:

Syntax of Interrupting a Thread:

The basic syntax for interrupting a thread is as follows:

thread.interrupt();

Example of Interrupting a Thread:

This example demonstrates how to create a thread that can be interrupted:

Code Example

class InterruptibleTask extends Thread {
    public void run() {
        try {
            while (!isInterrupted()) { // Check for interrupt status
                System.out.println("Thread is running...");
                Thread.sleep(1000); // Simulate work
            }
        } catch (InterruptedException e) {
            System.out.println("Thread was interrupted during sleep.");
        } finally {
            System.out.println("Cleaning up resources...");
        }
    }
}

public class InterruptExample {
    public static void main(String[] args) {
        InterruptibleTask task = new InterruptibleTask();
        task.start();

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

        // Interrupting the task thread
        task.interrupt();
        System.out.println("Main thread has interrupted the task thread.");
    }
}

Output:

Thread is running...
Thread is running...
Thread is running...
Thread was interrupted during sleep.
Cleaning up resources...

Conclusion:

Interrupting threads in Java is an essential feature for managing thread lifecycle and ensuring responsive applications. By implementing proper interruption handling, developers can design more robust and user-friendly multi-threaded applications.

Best Practices: