Home > database >  Thread with interruption in java
Thread with interruption in java

Time:02-02

I have a question about threads in Java.

I have the following code:

public static void main(String[] args) {
    Runnable r = () -> {
        while (!Thread.interrupted()) {
            System.out.println("Hola");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("interrupted");
                break;
            }
        }
    };

    Thread t = new Thread(r);
    t.start();

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

    t.interrupt();
}

Why if I introduce an interrupt does it still enter the loop? (without break).

I understand the operation of the thread when there is an exception.

CodePudding user response:

Whenever the sleep method detects an interruption it resets the interrupt flag before throwing an InterruptedException. So if you don't use break then the interrupt flag is set to false by the time the exception is caught and the while loop test never detects the interruption.

The recommended practice is to add a line to your catch block like this

Thread.currentThread.interrupt();

if you want to keep the interrupt status.

It's not a problem here but be aware that Thread.interrupted() resets the interrupt flag. It's a convenience method used by some JDK code so that resetting the interrupt flag and throwing the exception takes less code.

  • Related