JAVA

interrupt() in java threads

neal89 2025. 3. 9. 12:13

🔹 What is Thread Interruption?

In Java, interrupting a thread means signaling it to stop execution. However, interrupting a thread does not forcefully stop it—instead, it is up to the thread itself to handle the interruption and terminate properly.

Why Use Interruptions?

  • Stop a thread gracefully without forcing termination.
  • Wake up a sleeping or waiting thread.
  • Improve responsiveness in multi-threaded applications.

🚀 Example 1: Stopping a Thread Using a Flag (Without Interruption)

A common approach to stopping a thread is by using a boolean flag.

public class StopThreadWithFlag {
    public static void main(String[] args) {
        MyTask task = new MyTask();
        Thread thread = new Thread(task, "Worker");
        thread.start();

        try {
            Thread.sleep(4000); // Allow thread to run for 4 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Stopping the thread...");
        task.running = false; // Change the flag to stop the thread
    }

    static class MyTask implements Runnable {
        volatile boolean running = true;

        @Override
        public void run() {
            while (running) {
                System.out.println(Thread.currentThread().getName() + " is working...");
                try {
                    Thread.sleep(2000); // Simulate work
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " has stopped.");
        }
    }
}

🔹 Expected Output

Worker is working...
Worker is working...
Stopping the thread...
Worker has stopped.

🔹 Why is This Approach Not Ideal?

  • Delay in stopping: The thread only checks the flag after waking up from sleep().
  • Cannot stop waiting or blocked threads (e.g., Thread.sleep(), wait(), join()).
  • Less responsive if the thread is in a long-running task.

🚀 Example 2: Using interrupt() for Immediate Response

A better approach is to use thread interruption, which can break out of waiting states (e.g., sleep()).

public class InterruptThreadExample {
    public static void main(String[] args) {
        Thread worker = new Thread(new MyTask(), "Worker");
        worker.start();

        try {
            Thread.sleep(4000); // Allow thread to run for 4 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Interrupting the thread...");
        worker.interrupt(); // Send interrupt signal
    }

    static class MyTask implements Runnable {
        @Override
        public void run() {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + " is working...");
                    Thread.sleep(2000); // Simulate work
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " was interrupted.");
            }
            System.out.println(Thread.currentThread().getName() + " has stopped.");
        }
    }
}

🔹 Expected Output

Worker is working...
Worker is working...
Interrupting the thread...
Worker was interrupted.
Worker has stopped.

🔹 Why Is This Better?

  • The thread stops immediately when interrupted, instead of waiting for the next loop iteration.
  • It works even if the thread is in sleep(), wait(), or join().
  • More responsive than using a flag.

🚀 Example 3: Using Thread.interrupted() to Reset Interrupt Status

  • Thread.interrupted() checks if the thread was interrupted and resets the interrupt flag.
  • isInterrupted() checks the interrupt status without resetting it.
public class InterruptedFlagExample {
    public static void main(String[] args) {
        Thread worker = new Thread(new MyTask(), "Worker");
        worker.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Interrupting the thread...");
        worker.interrupt();
    }

    static class MyTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                if (Thread.interrupted()) { // Checks and resets interrupt flag
                    System.out.println(Thread.currentThread().getName() + " was interrupted!");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + " is working...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " was interrupted during sleep!");
                    break;
                }
            }
            System.out.println(Thread.currentThread().getName() + " has stopped.");
        }
    }
}

🔹 Expected Output

Worker is working...
Interrupting the thread...
Worker was interrupted!
Worker has stopped.

🔹 Key Observations

  • Thread.interrupted() resets the interrupt status after checking.
  • isInterrupted() would not reset the status.

✅ Summary of interrupt()

Method Description

interrupt() Signals the thread to stop. Does not forcefully terminate it.
isInterrupted() Checks if the thread was interrupted without resetting the flag.
Thread.interrupted() Checks if the thread was interrupted and resets the flag.
InterruptedException Thrown when an interrupted thread is in sleep(), wait(), join(), etc.

📌 When to Use interrupt()

  • When a thread is performing a long-running task and needs to stop gracefully.
  • When a sleeping or waiting thread needs to be woken up.
  • When handling user-requested cancellations in multi-threaded applications.

'JAVA' 카테고리의 다른 글

synchronized  (0) 2025.03.10
memory visibility & volatile  (0) 2025.03.09
join() in java thread  (0) 2025.03.09
Why Can't run() Throw Checked Exceptions?  (0) 2025.03.08
daemon thread  (0) 2025.03.07