Sobes.tech
Junior — Middle

Can you explain how the interruption mechanism works in threads or processes?

sobes.tech AI

Answer from AI

In Java, the thread interruption mechanism is used to signal a thread about the need to stop or change its behavior. An interruption does not stop the thread immediately but sets an interruption flag, which the thread should check and handle properly.

Main points:

  • The interrupt() method sets the interruption flag for a thread.
  • A thread can check its state using Thread.interrupted() or isInterrupted().
  • If the thread is in a waiting state (e.g., sleep(), wait()), calling interrupt() will throw an InterruptedException.

Example:

Thread thread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        // Perform work
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Thread was interrupted during sleep
            Thread.currentThread().interrupt(); // Restore the interruption flag
            break; // Exit the loop
        }
    }
    System.out.println("Thread finished");
});

thread.start();
// Interrupt the thread after some time
thread.interrupt();

Thus, interruption is a way to politely signal a thread about the need to finish or change its work, rather than forcibly stopping it.

Can you explain how the interruption mechanism works… - sobes.tech