Interrupt flow in java

I want to get clarification about thread interruption.

What if a thread lasts a long time without calling a method that throws an AnInruptedException? Then it should periodically call Thread.interrupted, which returns true if an interrupt is received. For instance:

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

When I call the method Thread.interrupt(), it throws an interrupted exception, so I need to do it if (Thread.interrupted()), I just do it

try {
    for (int i = 0; i < inputs.length; i++) {
        heavyCrunch(inputs[i]);
        if (Thread.interrupted()) {
            // We've been interrupted: no more crunching.
            return;
        }
    }
} catch (InterruptedException ex) {
        ...
}
+4
source share
3 answers

When you call Thread.interrupt()to another thread, two things happen:

  • The thread interrupt flag is set.
  • If a thread is blocked in a method throws InterruptedException, this method will immediately throw an exception.

, InterruptedException, . if (Thread.interrupted()), .

Java catch, try InterruptedException.

+4

Thread.interrupted(), , InterruptedException. true false , Thread.interrupt(). , Thread.interrupt() InterruptedException .

0

InterruptedException. , , . , sleep, wait join, , , InterruptedException.

, , , ; , , , .

Thread.isInterrupted(), . Thread.interrupted() :

. , , false ( , , ).

while Thread.isInterrupted() :

, . .

, , . Thread.isInterrupted(), Thread.interrupted() InterruptedException, , , .

In addition, Thread.interrupt does not throw an InterruptedException. (And any exception thrown would be in the calling thread, not in the interruption of the thread.) The interrupt method is used to set the interrupt flag in another thread. If the interruption of the thread itself is pointless, the thread may return instead.

0
source

Source: https://habr.com/ru/post/1531367/


All Articles