Java's Thread.interrupt() Unveiled
The java.lang.Thread.interrupt() method plays a crucial role in managing thread interruptions in Java. When invoked, it sets a flag indicating that the target thread should check its interrupted status.
How Interrupts Work
Interruptions are not pre-emptive in Java. Instead, the target thread must actively poll its interrupted status. To do so, it uses Thread.interrupted(), which returns the current thread's status and clears the interrupt flag. Typically, an interrupted thread will then handle the interruption appropriately, such as by throwing an InterruptedException.
Key Points
Predefined Interrupt Handling
Certain API methods, such as Object.wait(), Thread.sleep(), Thread.join(), java.util.concurrent structures, and Java NIO, have built-in interrupt handling. They consume the interrupt flag and throw appropriate exceptions (usually InterruptedException).
Non-Preemptive Nature
It's important to note that interruption in Java is a non-preemptive mechanism. Threads have the choice of whether or not to handle interrupts. This gentle approach allows threads to exit cleanly when desired. In contrast, methods like Thread.stop() forcefully terminate threads, which can lead to unpredictable or problematic outcomes.
The above is the detailed content of How Does Java's Thread.interrupt() Work and Why Isn't It Preemptive?. For more information, please follow other related articles on the PHP Chinese website!