Thread Interruption

Thread interruption in programming, particularly in languages like Java, refers to a mechanism where a thread is signaled to stop or pause its execution, typically to allow for graceful termination or to handle specific conditions. Here’s a concise overview based on standard concepts:

  • Interruption is a way to request a thread to stop what it’s doing. It doesn’t forcibly terminate the thread but sets a flag (the “interrupted” status) that the thread can check to decide how to proceed.
  • How It Works:
    • In Java, a thread can be interrupted using the interrupt() method on a Thread object.
    • This sets the thread’s interrupted flag to true.
    • The thread can check this flag using isInterrupted() or handle interruptions when certain blocking methods (e.g., sleep(), wait(), or join()) throw an InterruptedException.
  • Important Points:
    • Interruption is cooperative: the thread must periodically check its interrupted status or catch InterruptedException to respond appropriately.
    • Common practice is to exit the thread or clean up resources when interrupted.
    • If an InterruptedException is caught, the interrupted flag is cleared, so the thread may need to re-interrupt itself (Thread.currentThread().interrupt()) to preserve the interruption state.
Thread thread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        try {
            // Simulate work
            Thread.sleep(1000);
            System.out.println("Working...");
        } catch (InterruptedException e) {
            // Restore interrupted status
            Thread.currentThread().interrupt();
            System.out.println("Thread interrupted, exiting...");
            return;
        }
    }
});
thread.start();
Thread.sleep(3000); // Let it run for 3 seconds
thread.interrupt(); // Request interruptionCode language: JavaScript (javascript)

Program

In this program, if the thread is interrupted during sleep, an InterruptedException is thrown. The catch block re-interrupts the thread to preserve the interrupt status and exits the loop to stop the thread.

//ThreadInterruptDemo.java
class MyRunnable implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            // Perform some task
            System.out.println(Thread.currentThread().getName() + " is working...");
            try {
                // Simulate work with sleep
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // Re-interrupt the thread if interrupted during sleep
                System.out.println(Thread.currentThread().getName() + " was interrupted during sleep.");
                Thread.currentThread().interrupt();  // Set interrupt flag again
                break;  // Exit the loop to stop the thread
            }
        }
        System.out.println(Thread.currentThread().getName() + " is exiting.");
    }
}

public class ThreadInterruptDemo {
    public static void main(String[] args) {
        // Create a new thread with MyRunnable instance
        Thread thread = new Thread(new MyRunnable());
        
        // Start the thread
        thread.start();
        
        try {
            // Let the thread run for a few seconds
            System.out.println("Main thread is sleeping for 5 seconds...");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        // Interrupt the thread to stop its execution
        System.out.println("Main thread is interrupting the worker thread...");
        thread.interrupt();
        
        try {
            // Wait for the thread to finish
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        System.out.println("Main thread finished execution.");
    }
}

/*

C:\>javac ThreadInterruptDemo.java

C:\>java ThreadInterruptDemo
Main thread is sleeping for 5 seconds...
Thread-0 is working...
Thread-0 is working...
Thread-0 is working...
Thread-0 is working...
Thread-0 is working...
Main thread is interrupting the worker thread...
Thread-0 was interrupted during sleep.
Thread-0 is exiting.
Main thread finished execution.

*/

Interruption during Blocking Operations

This program demonstrates thread interruption in Java, showcasing how a main thread can interrupt a worker thread performing a blocking operation.
//BlockingTaskDemo.java
class BlockingTask implements Runnable {
    @Override
    public void run() {
        try {
            while (true) {
                // Simulate a blocking operation
                System.out.println("Worker Thread is running...");
                Thread.sleep(1000); // Simulate task
            }
        } catch (InterruptedException e) {
            // Handle the interruption
            System.out.println("Worker Thread was interrupted.");
        }
    }
}
public class BlockingTaskDemo {
    public static void main(String[] args) {
        // Create a new thread with BlockingTask instance
        Thread blockingThread = new Thread(new BlockingTask());
        
        // Start the thread
        blockingThread.start();
        
        try {
            // Let the thread run for a few seconds
            System.out.println("Main thread is sleeping for 3 seconds...");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        // Interrupt the thread to stop its execution
        System.out.println("Main thread is interrupting the worker thread...");
        blockingThread.interrupt();
        
        try {
            // Wait for the thread to finish
            blockingThread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        System.out.println("Main thread finished execution.");
    }
}

/*
C:\>javac BlockingTaskDemo.java

C:\>java BlockingTaskDemo
Main thread is sleeping for 3 seconds...
Worker Thread is running...
Worker Thread is running...
Worker Thread is running...
Main thread is interrupting the worker thread...
Worker Thread was interrupted.
Main thread finished execution.
*/

Thread interruption in Java is a cooperative mechanism that allows one thread to signal another to stop its current activity. It is not a direct way to stop a thread but a request for the thread to handle termination. Threads must check the interrupt status and respond by either terminating or continuing their tasks. Handling interruptions gracefully is crucial for proper resource management and clean shutdowns. Properly handling interruptions improves application responsiveness and reliability.

Scroll to Top