开发者

Will it better to use isInterrupted instead of interrupted in the following case

When I revise some old code, I came across.

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

        try {
            this.simulationThread.join();
        }
        catch (InterruptedExceptio开发者_如何学JAVAn exp) {
            log.error(null, exp);
        }

        this.simulationThread = null;
     }
}

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

I was wondering, will it better to use, or it doesn't 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) {
    }
}


It depends on what you intend to happen when run() exits. If your run() function is your main thread loop, such that you want that thread to exit immediately upon run() completing, then swallowing the interruption flag with Thread#interrupted() is fine.

Usually, though, that's not what you want to do. If you're trying to enable graceful exit of the run() function to allow cooperative cancellation, it's better form to preserve the interrupted flag for your caller and for downstream blocking functions to detect. For that, using Thread#isInterrupted() is the better choice.

Note that in your stop() function, where you catch InterruptedException, you should also call

Thread.currentThread().interrupt();

It's not clear from the snippets posted here who is calling stop() and what's supposed to happen afterward, but, again, it would be better form to preserve the interruption flag that popped stop() out of Thread#join(). Just catching InterruptedException allows stop() to react to that interruption, but no callers or following blocking functions would be able to detect that interruption request against the current thread. In other words, interrupting a thread is rarely satisfied by just unblocking one blocking function call; the interruption request usually needs to propagate all the way back out to the thread's main function so that it may exit.

Finally, is your simulationThread field volatile?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜