Overview
Before explaining the methods in the thread class, the interrupt (), Interrupted (), and isinterrupted () Three methods did not speak very clearly, only to mention a bit. Now put these three methods in the same place, because these three methods are related to a multi-threaded knowledge point----interrupt mechanism.
Java does not provide a secure, straightforward way to stop a thread, but instead provides an interrupt mechanism. The interrupt mechanism is a collaborative mechanism, meaning that the interrupt does not terminate the other thread directly, and the thread that needs to be interrupted is handled by itself . There is an example of a good, like parents told to go out of the children to pay attention to the body, parents said, but children pay attention to the body, how to pay attention to the body, or to see themselves.
The interrupt mechanism is the same, with each thread object having an identity bit indicating whether there is an interrupt request (of course JDK The source code is not see this identity bit, is the virtual machine thread implementation level), represents whether there is an interrupt request.
Three interrupt methods
As stated above, the interrupt identifier is not visible to the JDK source code, is the virtual machine thread implementation level. Here's a look at how these three methods work, together with the code, and why the interrupt identity bit is a virtual machine implementation level:
1, interrupt ()
1 Public voidinterrupt () {2 if( This!=Thread.CurrentThread ())3 checkAccess ();4 5 synchronized(blockerlock) {6Interruptible B =blocker;7 if(b! =NULL) {8Interrupt0 ();//Just to set the interrupt flag9 b.interrupt ();Ten return; One } A } - interrupt0 (); -}
1 /*Some Private Helper Methods*/2 Private native voidSetPriority0 (intnewpriority);3 Private native voidstop0 (Object o);4 Private native voidsuspend0 ();5 Private native voidRESUME0 ();6 Private native voidInterrupt0 ();
See in two parts:
(1) The 8th line of the first part of the note is very clear, the Interrupt0 () method is the role of "Just to set the interrupt flag", that is, the function of the method is simply to set the interrupt identifier bit
(2) The 6th line of the second part is the prototype of the Interrupt0 () method, because the method is native modified, it is obvious that this is a local method, is implemented by the Java Virtual machine
2, isinterrupted ()
The only function of the method is to test whether the thread has been interrupted, the state of the interrupt identity bit is not affected by the method, and see how Java implements this method:
1 /**2 * Tests Whether this thread has been interrupted. The <i>interrupted3 * status</i> of the thread is unaffected by this method.4 *5 * <p>a thread interruption ignored because A thread is not alive6 * at the time of the interrupt would be reflected by this method7 * Returning false.8 *9 * @return<code>true</code> If this thread has been interrupted;Ten * <code>false</code> otherwise. One * @see#interrupted () A * @revised 6.0 - */ - Public Booleanisinterrupted () { the returnIsinterrupted (false); -}
Private native boolean isinterrupted (boolean clearinterrupted);
Notice the 2nd and 3rd lines of the first section, "The interrupted statis of the thread is unaffected by this method", that is, the interrupt state of the thread is not affected by the approach. The final call is Isinterrupted (Boolean clearinterrupted), which is a native that can be seen in the Java Virtual Machine implementation. The parameter of the method clearinterrupted, as the name implies, clears the interrupt ID bit, passing false here, which is obviously not clear
3, Interrupted ()
the function of the method is to test whether the thread's interrupt identity bit is cleared by the method when the front-line thread has been interrupted . In other words, the return value of calling the method twice in a row must be false. Take a look at how this approach is implemented:
1 /**2 * Tests Whether the current thread has been interrupted. the3 * <i>interrupted status</i> of the thread is cleared by this method. Inch4 * Other words, if this method were to being called twice in succession, the5 * Second Call would return False (unless the current thread were6 * Interrupted again, after the first call had cleared its interrupted7 * Status and before the second call had examined it).8 *9 * <p>a thread interruption ignored because A thread is not aliveTen * at the time of the interrupt would be reflected by this method One * Returning false. A * - * @return<code>true</code> If the current thread has been interrupted; - * <code>false</code> otherwise. the * @see#isInterrupted () - * @revised 6.0 - */ - Public Static Booleaninterrupted () { + returnCurrentThread (). isinterrupted (true); -
Private native boolean isinterrupted (boolean clearinterrupted);
Similarly, the comments on lines 2nd and 3rd have been clearly written, "The interrupted status of the thread is cleared by this method", that is, the interrupt state of the thread is cleared by the methods. In addition, the interrupted () method and the Isinterrupted () method call are the same native method, but this method is passed true, which means that the interrupt ID bit is cleared
In addition, the methods of some classes in the JDK API may also invoke interrupts, such as Futuretask's Cancel, which, if passed in true, invokes the interrupt () method on the running asynchronous task. Again, as in Threadpoolexecutor, the Shutdownnow method iterates through the worker threads in the thread pool and calls the thread's interrupt () method. In these scenarios, the task continues as long as the code does not respond to interrupts.
Interrupt processing Time
This is actually a very broad topic that has no answer. Obviously, as a collaboration mechanism, the interrupted thread must not be forced to interrupt processing at a certain point. In fact, the interrupted thread only needs to be processed at the right time, if there are no suitable points of point, and can not even be handled. The "Right point in time" is closely related to business logic.
The processing time determines the efficiency of the program and the sensitivity of the response. Frequent check interruptions can lead to inefficient execution of programs, and fewer checks can cause interrupt requests to not respond in a timely manner. In a real-world scenario, if the performance metrics are critical, you may need to establish a test model to analyze the best interrupt detection points to balance performance and responsiveness .
Example of thread interruption
Write so many theories and write an example to illustrate the interruption:
Public Static voidMain (string[] args)throwsexception{Runnable Runnable=NewRunnable () { Public voidrun () { while(true) { if(Thread.CurrentThread (). isinterrupted ()) {System.out.println ("The thread has been interrupted"); return ; } Else{System.out.println ("Thread not Interrupted"); } } } }; Thread T=NewThread (runnable); T.start (); Thread.Sleep (3000); T.interrupt (); System.out.println ("The thread is broken, the program is here.");}
Look at the results of the operation:
... Thread is not interrupted thread is not interrupted thread is not interrupted thread is not interrupted thread is not interrupted thread is interrupted, program here is broken thread
The code is divided into the following steps:
1. The main function plays a T thread
2, the main function 3 seconds after the T-thread to hit an interrupt identification bit, indicating that the T thread to break
3, T thread Unlimited polling their own interrupt identification bit, interrupted to print, exit, or continue to run
The statement printed from the console saw that after 3 seconds of interruption, the printed statement was printed and stopped. That scenario is the " frequent check " that is said earlier, which causes the program to be inefficient; If you do not check frequently, such as by adding Thread.Sleep (500) to the Else branch in the while, Indicates that 500ms is the 0.5s check once, then this scenario is said earlier, "the interruption is not a timely response ."
In fact, in this example, the T thread completely can not take care of this interrupt identity bit, do not check on the good, just do their own things, this shows that the interrupt identity bit set is not a thing other people's things, do not handle is my own thing, there is no mandatory requirement to deal with the interruption.
However, those that would throw interruptedexception are excluded. Like Sleep, wait, notify, join, these methods encounter interrupts must have corresponding measures, can be processed directly in the catch block, or can be thrown to the previous layer. These methods are thrown interruptedexception is because the Java virtual machine in the implementation of these methods, there is a mechanism in itself to determine the interrupt identity bit, if interrupted, throw a interruptedexception.
Java Multi-Threading 17: Interrupt mechanism