当前位置:网站首页>Detailed description of thread interrupt() thread interrupt

Detailed description of thread interrupt() thread interrupt

2020-12-07 20:42:40 itread01

[GitHub Original code address ](https://github.com/DearZh/smart-heart/blob/master/example/src/main/java/com/smart/heart/java/lock/thread/ThreadStopTest.java) [ Original announcement : author :Arnold.zhao Blog Park Address :https://www.cnblogs.com/zh94](https://www.cnblogs.com/zh94) One thread should not be forced to interrupt or stop by other threads , It's up to the thread to stop itself . therefore ,Thread.stop, Thread.suspend, Thread.resume It's been abandoned .Java Thread.interrupt() Method provides a thread break , Actually, from the outside of the thread , Modify a flag variable inside the thread , Or let some blocking methods in the thread , Throw InterruptedException. In this way ” notice “ Thread to do something , What to do , Do not do , It's really entirely up to the business code in the thread itself . However, it is usually to release resources and end the thread . ## Basic concepts ``` public static void basic() { Thread testThread = new Thread(new Runnable() { @Override public void run() { System.out.println(); } }); testThread.interrupt(); // Is to set the interrupt flag for the thread ; Its function is to interrupt this thread ( This thread is not necessarily the current thread , It refers to the Thread The thread represented by the instance ) testThread.isInterrupted(); // Only detect interrupts ; Apply to this thread , That is, the thread represented by the instance item in the code that calls this method ; The function is to test whether the thread is interrupted , Do not clear interrupt status . testThread.interrupted(); // Is to detect interrupts and clear interrupt status ; Apply to the current thread ( The function is to test whether the current thread is interrupted ( Check the interrupt flag ), Back to a boolean And clear the interrupt state , The interrupt status has been cleared on the second call , Will return to a false) Thread.interrupted(); // ditto //************************************ testThread.interrupt(); // Set the designation testThread The state of the thread is the interrupt flag , testThread.isInterrupted();// Detect current testThread Whether the thread is interrupted by the outside world ; Yes, go back to true testThread.interrupted();// Detect current testThread Whether the thread receives interrupt signaling , When the signal is received, it returns true And clear the interrupt state , Change it to false; Thread.interrupted();// Static method , And testThread.interrupted() The same thing ,( Detect current testThread Whether the thread is interrupted , If interrupted, return to true And clear the interrupt state , Change back to uninterrupted state ;) Applied to the currently executed thread , Because of testThread When the internal thread is running , It's impossible to get testThread Refer to the , So if you want to detect whether your thread is interrupted and clear the interrupt state , You can use Thread.interrupted() Method ; // Above , In fact, there are only three methods for thread interruption , among interrupt() and isInterrupted() Is the thread instance method ,interrupted() It's the static method of the thread ; //isInterrupted() Is the thread instance method , therefore , The thread is not able to get from the running code inside the thread testThread The instance method cannot be executed because it is referenced by isInterrupted(); // But in fact , We can use it in the internal program execution code Thread.currentThread() Gets the instance item of the current thread , Use Thread.currentThread().isInterrupted() The way to call isInterrupted() Method ; Equivalent to testThread.isInterrupted(); // Equivalence and : The thread is used for external detection :testThread.isInterrupted(); Internal thread for detection :Thread.currentThread().isInterrupted() } ``` ## Thread break validation ``` /** * Verify that in general use interrupt() An example of a thread interrupt */ public static void threadStopTest() { Thread testThread = new Thread(new Runnable() { @Override public void run() { // The first situation : Detects whether the thread receives interrupt signaling , Return when you receive it true, And clear the current thread state , Change back to uninterrupted ; /* while (!Thread.interrupted()) { System.out.println(" In thread code execution "); } // At this time, we will check whether the thread receives the external interrupt signal , The result is false, Because of the use of Thread.interrupted(), After receiving the interrupt signal , Will clear the current thread state , So when judging here, the return result is false, Thread state did not receive interrupt signaling System.out.println(Thread.currentThread().isInterrupted()); System.out.println(Thread.currentThread().isInterrupted()); */ // The second situation : Detects whether the thread receives interrupt signaling , Return when you receive it true, It just detects whether the interrupt signaling is currently received , Does not clear the current thread state , while (!Thread.currentThread().isInterrupted()) { System.out.println(" In thread code execution "); } // At this time, it detects whether the current thread receives external interrupt signaling ,true To indicate receipt of , The result obtained here is true System.out.println(Thread.currentThread().isInterrupted()); //true System.out.println(Thread.currentThread().isInterrupted()); //true // The thread is interrupted and the code block is executed , Recycling work System.out.println(" Thread received external interrupt notification , Internal thread recycling has been performed , Interrupt complete "); /*while (true) { }*/ } }); testThread.start(); try { Thread.sleep(5000); // wait for 5 Seconds later Send out interrupt signal , notice testThread Thread interrupts testThread.interrupt(); // Determine whether the thread currently interrupts completion boolean flag = true; int index = 0; Thread.sleep(1000); while (flag) { // Gets whether the specified thread receives an interrupt signal , return true Indicates that the thread has received an interrupt signal , But the thread is running , Processing ; Or the interrupt signal has been received , But chose to continue execution without interruption ; // If you return false There are two situations //1、 The thread has finished executing , Finish interrupt ; Since the thread has finished executing at this time , Then, when the thread's signaling is obtained here, it will return to false, //2、 The thread did not complete the interrupt , But the thread code uses Thread.interrupted() Clear the signaling state of the thread , In this case, the result is returned false, System.out.println(" Detect thread interrupts :" + testThread.isInterrupted()); // Loop test 10 Second ,10 Seconds later, you jump out of the loop Thread.sleep(1000); index++; if (index == 10) { // Stop testing flag = false; } } if (!testThread.isInterrupted()) { //TODO: testThread Thread interrupt completion , The code block is executed System.out.println(" External detection testThread Interrupt complete "); } else { //TODO: Otherwise , Run another code block System.out.println(" External detection testThread Interrupt failed "); } } catch (InterruptedException e) { e.printStackTrace(); } } ``` [ Original announcement : author :Arnold.zhao Blog Park Address :https://www.cnblogs.com/zh94](https://www.cnblogs.com/zh94) ## Verify thread break , Throw InterruptedException Abnormal conditions ``` /** * Verify thread break , Throw InterruptedException Abnormal conditions ; */ public static void threadStopTest2() { /** * When an external call signals the interrupt of the thread , If the thread is in a blocked state , Such as ;Thread.sleep(),Object.wait(),BlockingQueue#put、BlockingQueue#take etc. * Then by calling the current thread object interrupt Method to trigger the throw of these functions InterruptedException Abnormal . * When a function is thrown InterruptedException When it's abnormal , This method has been blocked for too long , The external application doesn't want to wait for its execution to finish . * When you catch a InterruptedException After the abnormality , You can also deal with it , Or throw it up . * * Be careful when throwing ???: When you catch InterruptedException After the abnormality , The interrupt state of the current thread has been changed to false; * At this point, if you can handle interrupts , Normal end thread , The value is ignored ; But if you keep throwing up InterruptedException Abnormal , You need to call again interrupt Method , Set the interrupt state of the current thread to true. * */ Thread testThread = new Thread(new Runnable() { @Override public void run() { try { // External call signaling , To interrupt the thread , If the thread is sleeping or blocking at this time , Will throw exception Thread.sleep(6000); } catch (InterruptedException e) { // The first situation : Enter exception capture , Exception caught here , Indicates that the thread is currently interrupted by an external request , At this point, we can choose to interrupt the thread ; Then the following while The loop will not be executed , The thread is finished , End ; /*if (1 > 0) { return; } */ // The second situation : Of course , We can also choose to receive interrupt signaling after , No thread breaks ; such as , The current thread is indeed in a normal blocking period , After the blocking is complete , I still have to execute while Circle back , At the end of the day while After loop back execution , To end the thread's life cycle normally ; // Then at this time , After catching the exception, do nothing ; It should be noted that , At this point InterruptedException After the abnormality , The thread state will be automatically changed to false // (false Indicates that the thread has not received interrupt signaling , Or the thread has been interrupted , Or the thread uses Thread.interrupted() Cleared the signaling state ) No interrupt signaling has been received, which is basically impossible , As long as there is an external call , Then 100% of the signaling is received , Except before the call interrupt signaling , Get the state of the thread , At this point, it must be false Of ; Such as : Execute first ,testThread.isInterrupted(), Reexecution testThread.interrupt(); At this point, the first one to execute isInterrupted() Must be false, This scene doesn't mean much ; //1、 To the outside world , The signaling status of the received thread is false, Indicates that the thread has completed execution ; Of course, the stored route signaling is false It is the internal thread that makes the transformation itself , But it doesn't actually stop the thread from running ; // So in general , According to the agreement , If the internal thread receives an interrupt request , At this point, if you need to continue , Ignore external interrupt signaling , Then you can execute :Thread.currentThread().interrupt(); Re convert the internal state to true // So , When the external thread re detects the signaling state of the current thread true When , Then we know , The internal thread has received an interrupt signal , Instead of never receiving interrupt signaling . // Here is false, After catching the interrupt exception , Will automatically change the thread state to false, System.out.println(" Abnormal " + Thread.currentThread().isInterrupted()); // Here, because you want to continue running the thread , Do not run thread breaks , So change the interrupt status to true; Thread.currentThread().interrupt(); // At this time, the result is true; System.out.println(" Abnormal " + Thread.currentThread().isInterrupted()); } while (true) { System.out.println(" The thread is running internally "); } } }); testThread.start(); // Issue thread interrupt signaling testThread.interrupt(); } ``` ## Make an appointment ``` /** * Make an appointment : * Internal interrupt threads , If you need to continue , The signaling status must be reset to true; At this point, the external caller will know that the current thread has received the interrupt signal, but it will continue to execute ; *

* Under what circumstances , The thread state is automatically changed to false? *

* 1、 After the thread is automatically executed , The status will be automatically set to false; * 2、 Internal use of threads :Thread.interrupted() Method to get thread state , Will automatically clear the thread state , Changes the current thread state to false; * 3、 If the thread captures ,InterruptedException Abnormal , Then the thread state will be automatically changed to false; *

* therefore , * 1、 If using Thread.interrupted() To get the thread state , After using it , It must be ensured that the thread is normally interrupted ; If there is no guarantee , Recommended Thread.currentThread().isInterrupted() To get the thread state ;isInterrupted() Method only gets the thread state , Does not change the thread state ; * 2、 For in thread use try catch Caught InterruptedException Abnormal conditions , After the capture , Be sure to do something about it , Instead of just catching exceptions , But the interrupt signaling is not processed ; * After the exception is currently caught , If you need to interrupt , You can interrupt the thread directly * After the exception is currently caught , If you don't need to interrupt , Need to continue thread execution , Then you need to execute Thread.currentThread().interrupt(); Change your thread state to true, Indicates that the current thread needs to continue running ; * After the exception is currently caught , If you don't need to interrupt , Instead, the anomaly is thrown out to the upper method for processing , Then it needs to be carried out at this time Thread.currentThread().interrupt(); Change your thread state to true, Indicates that the current thread needs to continue running ; */ public static void main(String[] args) throws InterruptedException { // threadStopTest(); /* Thread.currentThread().interrupt(); System.out.println(Thread.currentThread().isInterrupted());true System.out.println(Thread.currentThread().isInterrupted());true System.out.println(Thread.currentThread().isInterrupted());true System.out.println(Thread.interrupted());true System.out.println(Thread.currentThread().isInterrupted());false System.out.println(Thread.interrupted());false */ } ``` [ Original announcement : author :Arnold.zhao Blog Park Address :https://www.cnblogs.com/zh94](https://www.cnblogs.c

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207204210403i.html