Thread类interrupted()与isInterrupted()方法行为差异原因探究
Thread.interrupted() Clears Interrupt State While isInterrupted() Doesn't? Great question! This design choice in Java's Thread API is all about catering to two distinct, common use cases for thread interruption, and keeping responsibilities clear between them. Let's break it down:
Thread.interrupted()is for the thread itself to handle interruption
When a thread receives an interrupt signal, it's typically expected to respond to that signal—maybe by wrapping up its task, cleaning up resources, and exiting gracefully. The staticinterrupted()method lets the thread check if it's been interrupted and clears the state in one step. This makes sense because once the thread has acknowledged and is acting on the interrupt, there's no need to keep that flag set anymore. If the state wasn't cleared, subsequent calls to interrupt-sensitive methods (likeThread.sleep()orObject.wait()) would immediately throw anInterruptedException, even after the thread has already handled the original interrupt.For example:
while (!Thread.interrupted()) { // Do some work try { Thread.sleep(100); } catch (InterruptedException e) { // Acknowledge the interrupt and exit Thread.currentThread().interrupt(); // Re-set if we need to propagate, but often we just exit break; } }Here,
Thread.interrupted()checks the state and clears it, so if the loop continues (unlikely in this case), it won't keep triggering the interrupt check unnecessarily.isInterrupted()is for external threads to query state without interfering
Sometimes you need another thread to check if a target thread is interrupted—think of a monitoring thread in a thread pool, or a parent thread checking on a child task's status. In these cases, you don't want to modify the target thread's interrupt state! The non-staticisInterrupted()lets you peek at the flag without altering it, so the target thread can still respond to the interrupt on its own terms later.For instance, a thread pool manager might do something like:
if (workerThread.isInterrupted()) { // Mark this worker as needing replacement, but let it finish cleaning up first reassignTasks(workerThread); }If
isInterrupted()cleared the state, the worker thread would never know it was supposed to stop, leading to unexpected behavior.
At the end of the day, this separation of concerns ensures that each method serves its intended purpose perfectly: one lets a thread handle its own interrupt cleanly, the other lets external code monitor interrupt state without disrupting the target thread's workflow.
内容的提问来源于stack exchange,提问作者PriMe

