There are three methods in the Java Thread class, which are easy to confuse.
(1) interrupt: sets the thread interruption status
(2) isinterrupt: indicates whether the thread is interrupted.
(3) interrupted: return the last interruption status of the thread and clear the interruption status.
For example:
Usage: <br/> class mythread extends thread {<br/> ...... <br/> ...... <br/> Public void run () {<br/> try {<br/> while (! Thread. currentthread (). isinterrupted () {<br/> // when the queue capacity is reached, locksupport is called internally. park () is the method used to block the thread <br/> // when other threads call the interrupt () method of this thread, an interrupt flag is set <br/> // locksupport. when this interrupt flag is detected in part (), interruptedexception is thrown and thread interruption flag is cleared. <br/> // Therefore, thread is called in the exception section. currentthread (). isinterrupted () returns false <br/> arrayblockingqueue. put (somevalue); <br/>}< br/>} catch (interruptedexception e) {<br/> // The library function is blocked, such as: object. wait, thread. sleep not only throws an exception, but also clears the thread interruption status. Therefore, the thread interruption status may be retained here. <br/> thread. currentthread (). interrupt (); <br/>}< br/> Public void cancel () {<br/> interrupt (); <br/>}< br/> external call <br/> mythread thread = new mythread (); <br/> thread. start (); <br/> ...... <br/> thread. cancel (); <br/> thread. isinterrupted ();
In general, blocking functions, such as thread. sleep, thread. join, object. wait, locksupport. park will throw interruptedexception and clear the thread interruption status when checking the thread interruption status.
Interruptedexception can be processed in two cases:
(1) The outer code can handle this exception and directly throw this exception.
(2) If this exception cannot be thrown, for example, in the run () method, the thread interruption status has been cleared when the exception is obtained, to retain the thread interruption status, you must call the thread. currentthread (). interrupt ()
In addition, thread. interrupted () is commonly used in the source code of the JDK library, because it can get the interrupt mark value of the last thread and clear the interrupt mark of the thread at the same time, but at the same time, this function also has the side effects of clearing the interrupt state, which is hard to understand.