Three methods and examples of Java multithreading interrupt mechanism
summary
When explaining the methods in the thread class, the interrupt (), interrupted (), isinterrupted () methods were not clearly explained, but just mentioned. Now let's put these three methods together here, because these three methods all involve a knowledge point of multithreading - interrupt mechanism.
Java does not provide a safe and direct way to stop a thread, but provides an interrupt mechanism. Interrupt mechanism is a kind of cooperation mechanism, that is to say, through interrupt, another thread cannot be terminated directly, but needs to be handled by the interrupted thread itself. For example, it's very good. Just like parents tell their children to pay attention to their health when they go out, the parents said, but whether and how their children pay attention to their health depends on themselves.
The interrupt mechanism is the same. Each thread object has an identification bit to indicate whether there is an interrupt request (of course, this identification bit cannot be seen in the JDK source code, which is at the virtual machine thread implementation level), representing whether there is an interrupt request.
Three interrupt methods
As mentioned above, the interrupt identification bit is invisible to the JDK source code and is the implementation level of virtual machine threads. Let's take a look at the functions of these three methods one by one in combination with the code, and why the interrupt identification bit is at the virtual machine implementation level:
1、interrupt()
result
It is divided into two parts:
(1) The comment on line 8 of the first part makes it clear that the function of the interrupt0 () method is "just to set the interrupt flag", that is, the function of the method is only to set the interrupt flag bit
(2) Line 6 of the second part is the prototype of the interrupt0 () method. Since the method is modified by native, it is obviously a local method implemented by the Java virtual machine
2、isInterrupted()
The only function of this method is to test whether the thread has been interrupted. The state of the interrupt identification bit is not affected by this method. Let's see how Java implements this method:
Note lines 2 and 3 of Part 1, "the interrupted status of the thread is unaffected by this method", that is, the interrupt status of the thread is not affected by this method. Finally, isinterrupted (Boolean clearinterrupted) is called. This method is native. It can be seen that it is also implemented by Java virtual machine. The parameter clearinterrupted of the method, as the name suggests, clears the interrupt flag bit. If false is passed here, it is obviously not cleared
3、interrupted()
Method is used to test whether the current thread has been interrupted. The interrupt identification bit of the thread is cleared by this method. In other words, the return value of calling the method twice in a row must be false. Let's see how this method is implemented:
Similarly, the comments on lines 2 and 3 have been clearly written, "the interrupted status of the thread is cleared by this method", that is, the interrupt status of the thread is cleared by this method. In addition, the interrupted () method and isinterrupted () method call the same native method, but the method passes in true, indicating that the interrupt identification bit is cleared
In addition, methods of some classes in jdkapi may also call interrupts, such as cancel of futuretask. If true is passed in, the interrupt () method will be called on the running asynchronous task. For example, the shutdown now method in ThreadPoolExecutor will traverse the working thread in the thread pool and call the interrupt () method of the thread. In these scenarios, the task will continue as long as the code does not respond to the interrupt.
Interrupt processing timing
This is actually a very broad topic without marked answers. Obviously, as a cooperation mechanism, the interrupted thread will not be forced to interrupt at a certain point. In fact, the interrupted thread only needs to be processed at the right time. If there is no right time point, it can not even be processed. The "right point in time" is closely related to the business logic.
The processing timing determines the efficiency of the program and the sensitivity of the response. Frequent inspection interruptions may lead to inefficient program execution, and less inspection may lead to the failure of timely response to interrupt requests. In the actual scenario, if the performance index is critical, it may be necessary to establish a test model to analyze the best interrupt detection point to balance performance and response sensitivity.
Thread interrupt example
After writing so many theories, write an example to demonstrate the interrupt:
Take a look at the running results:
The code is divided into the following steps:
1. The main function starts a t thread
2. The main function prints an interrupt flag to the T thread after 3 seconds, indicating that the T thread wants to interrupt
3. T thread polls its interrupt identification bit indefinitely. If it is interrupted, it will print and exit, otherwise it will run all the time
It can be seen from the statement printed on the console that it stops after printing the printed statement after 3 seconds of interruption. This scenario is called "frequent checking", which leads to low program efficiency; What if you do not check frequently, such as adding thread to the else branch in while Sleep (500), which means to check every 500 ms, that is, every 0.5 s. this scenario is the aforementioned "interruption can not get a timely response".
In fact, in this example, the T thread can completely ignore the interrupt flag bit and just do its own thing without checking it. This shows that whether the interrupt flag bit is set or not is someone else's business, whether it is handled or not is my own business, and there is no mandatory requirement to handle interrupts.
Except those methods that throw interruptedexception. For example, sleep, wait, notify and join, when these methods encounter an interrupt, they must have corresponding measures, which can be processed directly in the catch block or thrown to the upper layer. The reason why these methods throw interruptedexceptions is that when implementing these methods, the Java virtual machine itself has a mechanism to judge the interrupt identification bit. If an interrupt is thrown, an interruptedexception will be thrown.
summary
The above is all about the three methods and examples of Java multithreaded interrupt mechanism in this paper. I hope it will be helpful to you. Interested friends can continue to refer to this website:
Principle and implementation of Java Multithread timer
Java multithreading programming socket communication example code
Java uses future to get multithreading results in time