Would it be better to use isInterrupted instead of interrupting in the following case

When I review the old code, I came across it.

public void stop() {
    if (this.simulationThread != null) {
        this.simulationThread.interrupt();

        try {
            this.simulationThread.join();
        }
        catch (InterruptedException exp) {
            log.error(null, exp);
        }

        this.simulationThread = null;
     }
}

public void run() {
    while (!Thread.interrupted() && simulationThread == Thread.currentThread()) {
    }
}

I was wondering if it would be better to use, or does it not matter?

public void run() {
    Thread t = Thread.currentThread();
    // Will it better to use isInterrupted, since it will not clear the interrupt
    // flag?
    while (!t.isInterrupted() && simulationThread == t) {
    }
}
+3
source share
1 answer

It depends on what you intend to happen when it run()finishes work. If your function run()is your main thread loop, so you want this thread to exit immediately after completion run(), then swallowing the interrupt flag with Thread#interrupted()is ok.

, , . run(), , . Thread#isInterrupted().

, stop(), InterruptedException,

Thread.currentThread().interrupt();

, stop() , , , , stop() Thread#join(). InterruptedException stop() , . , ; , .

, simulationThread ?

+2

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


All Articles