There are three methods in the threading thread class of Java, which is easy to confuse, explain here
(1) Interrupt: Interrupt state of the thread
(2) Isinterrupt: Thread is interrupted
(3) Interrupted: Returns the last interrupt state of the thread and clears the interrupt state
As an example:
[Java]View Plaincopy
- Usage:
- class MyThread extends Thread {
- ......
- ......
- Public void run () {
- Try {
- while (! Thread.CurrentThread (). isinterrupted ()) {
- //When the queue capacity is reached, it is blocked here
- The inside of the//put calls Locksupport.park (), which is the method used to block the thread.
- //When other threads call this thread's interrupt () method, an interrupt flag is set
- //locksupport.part () detects this interrupt flag, throws Interruptedexception, and clears the thread's interrupt flag
- ///So call Thread.CurrentThread () in the exception segment. Isinterrupted () returns to false
- Arrayblockingqueue.put (somevalue);
- }
- } catch (interruptedexception e) {
- ///due to blocking library functions, such as: Object.wait,thread.sleep also clears the thread break state in addition to throwing exceptions, so it is possible to keep the interrupt state of the thread here
- Thread.CurrentThread (). interrupt ();
- }
- }
- Public void cancel () {
- Interrupt ();
- }
- }
- External calls
- MyThread thread = new MyThread ();
- Thread.Start ();
- ......
- Thread.cancel ();
- Thread.isinterrupted ();
In general, blocking functions, such as: Thread.Sleep, Thread.Join, object.wait, Locksupport.park, such as when checking the interrupt state of a thread, throws interruptedexception and clears the interrupt state of the thread.
There are two possible scenarios for interruptedexception processing:
(1) The outer code can handle this exception and throw the exception directly.
(2) If the exception cannot be thrown, such as in the Run () method, because the interrupt state of the thread is cleared when the exception is obtained, and the interrupt state of the thread needs to be preserved, call Thread.CurrentThread (). Interrupt ()
In addition, thread.interrupted () in the JDK Library source code is more commonly used, because it can get the interrupt flag value of the last thread, but also can clear the interrupt flag of the thread, double benefit, but there are disadvantages, that is, this function has the side effect of clearing the interrupt state, not easy to understand
interrupt,isinterrupt,interrupted Methods in Java threads