🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Interrupting Thread Methods in Java  


Introduction
  • Thread Interruption in Java is a mechanism to signal a thread that it should stop what it is doing and handle the interruption gracefully.
    • A thread is not forcibly stopped when interrupted.
    • Instead, it receives an interruption signal, which it can:
      • Detect by checking its interrupted status (isInterrupted() / interrupted()).
      • Respond by throwing an InterruptedException if blocked in sleep(), wait() or join().
  • Why we need to interrupt a thread:
    • Stop long-running tasks: Allows safely stopping threads that may run indefinitely or are waiting on blocking operations.
    • Responsive programs: Lets threads react to user requests or system shutdowns without abruptly killing them.
    • Resource management: Helps release resources like file handles, network connections or locks if a thread needs to stop.
  • Use of Thread Interruption in Projects:
    • Web servers: Interrupt worker threads when a client disconnects or cancels a request.
    • Background services: Stop background tasks gracefully during application shutdown or updates.
    • Multithreaded applications: Control thread execution, avoid deadlocks, and allow threads to terminate properly instead of using stop().
    • Task scheduling frameworks: Cancel running tasks in thread pools when they are no longer needed.
  • Java has provided the below Thread Interruption related methods in the Thread class:
    1. public void interrupt()
      • This method is used to interrupt a thread by sending a signal to it.
      • If the thread is in sleep(), wait() or join(), it will throw an InterruptedException.
      • If the thread is running normally, its interrupted status is set to true, which the thread can check using isInterrupted() or interrupted().
    2. public boolean isInterrupted()
      • This method checks whether the thread has been interrupted.
      • It does not clear the interrupted status of the thread.
      • Can be used by a thread to periodically check its interrupted status and take appropriate action.
    3. public static boolean interrupted()
      • This static method checks whether the current thread has been interrupted.
      • It clears the interrupted status after checking.
      • Useful to detect interruption and reset the status at the same time, often inside loops or blocking operations.
  • Program 1 - interrupt():
    class MyThread1 extends Thread
    {
        public void run()
        {
            try
            {
                for (int i = 1; i <= 5; i++)
                {
                    System.out.println(i);          // Print the value of i
                    Thread.sleep(1000);             // Sleep for 1 second
                }
            }
            catch(InterruptedException e)
            {
                System.out.println("Thread Interrupted, stopping task gracefully...");
            }
        }
    }
    
    public class MainApp1
    {
        public static void main(String[] args)
        {
            MyThread1 t = new MyThread1(); // Create a new thread
            t.start();                     // Start the thread
            t.interrupt();                 // Interrupt the thread
        }
    }
  • Program 2 - isInterrupted() and interrupted():
    class MyThread2 extends Thread
    {
        public void run()
        {
            // Interrupt the current thread manually
            Thread.currentThread().interrupt();
    
            // First check using interrupted() -> true, then resets flag
            System.out.println("First check with interrupted(): " + Thread.interrupted());
    
            // Second check using interrupted() -> false, because flag was cleared
            System.out.println("Second check with interrupted(): " + Thread.interrupted());
    
            // Now set interrupt flag again
            Thread.currentThread().interrupt();
    
            // Check with isInterrupted() -> true, does not reset flag
            System.out.println("First check with isInterrupted(): " + Thread.currentThread().isInterrupted());
    
            // Check again with isInterrupted() -> still true
            System.out.println("Second check with isInterrupted(): " + Thread.currentThread().isInterrupted());
        }
    }
    
    public class MainApp2
    {
        public static void main(String[] args)
        {
            MyThread2 mt = new MyThread2();
            mt.start();
        }
    }
  • Important Key Points about Interrupting a Thread:
    • Thread interruption in Java is a mechanism to signal a thread that it should stop its current work.
    • Calling interrupt() on a thread does not forcibly stop it; it only sets the interrupt flag.
    • If the thread is in a blocking state like sleep(), wait(), or join(), it immediately throws an InterruptedException.
    • If the thread is running normally, no exception is thrown; only the interrupt flag is set to true.
    • The thread can check its interrupt status by using:
      • Thread.interrupted() → checks and clears the interrupt flag.
      • isInterrupted() → checks the flag but does not clear it.
    • Interrupt methods are useful for safely stopping long-running tasks instead of using the unsafe stop() method.
    • The actual response to an interrupt depends on the thread’s code — the thread must cooperate by handling the InterruptedException or checking the flag.