Share one: the difference between interrupt, interrupted and isInterrupted, well written


1. The interrupt()
interrupt method is used to interrupt the thread. The state of the thread calling this method is to be placed in the "interrupted" state.
Note: Thread interrupts only set the thread's interrupt status bit, and do not stop the thread. The user needs to monitor the status of the thread and deal with it. The method that supports thread interruption (that is, the method that throws interruptedException after the thread is interrupted) is to monitor the interrupted state of the thread. Once the interrupted state of the thread is set to "interrupted state", an interrupted exception will be thrown.


2. interrupted() and isInterrupted()

First look at the implementation of this method in the API:
1 public static boolean interrupted () {
2 return currentThread().isInterrupted(true);
3 }
This method is to directly call isInterrupted( of the current thread) true) method.
Then look at the implementation of isInterrupted in the API:
1 public boolean isInterrupted () {
2 return isInterrupted( false);
3 }
This method directly calls the isInterrupted(false) method of the current thread.

So there are two main differences between the two methods:
interrupted is applied to the current thread, and isInterrupted is applied to the thread corresponding to the thread object that called the method. (The thread corresponding to the thread object is not necessarily the currently running thread. For example, we can call the isInterrupted method of the thread B object in thread A.)
These two methods will eventually call the same method-----isInterrupted( Boolean parameter ), except that one parameter is fixed to be true and the other is false; Note: isInterrupted (Boolean parameter) is an overloaded method of isInterrupted( ).

Since the second difference is mainly reflected in the parameters of the called method, let's take a look at what this parameter means.

First at the called method isInterrupted(boolean arg) (overloaded method in the Thread class). Definition:
1 private native boolean isInterrupted( boolean ClearInterrupted);
It turns out that this is a local method, and the source code cannot be seen. But it doesn't matter, we can know through the parameter name ClearInterrupted that this parameter represents whether to clear the status bit.
If this parameter is true, it means that after returning the status bit of the thread, the original status bit should be cleared (restored to the original situation). This parameter is false, which directly returns the status bit of the thread.

These two methods are very distinguishable. Only the current thread can clear its own interrupt bit (corresponding to the interrupted() method),



so I wrote an example to verify it:



public class Interrupt { 
    public static void main(String[] args) throws Exception { 
        Thread t = new Thread(new Worker()); 
        t.start(); 
         
        Thread.sleep(200); 
        t.interrupt(); 
         
        System.out.println("Main thread stopped."); 
    } 
     
    public static class Worker implements Runnable { 
        public void run() { 
            System.out.println("Worker started."); 
             
            try { 
                Thread.sleep(500); 
            } catch (InterruptedException e) { 
                System.out.println("Worker IsInterrupted: " +  
                        Thread.currentThread().isInterrupted()); 
            } 
             
            System.out.println("Worker stopped."); 
        } 
    } 

The content is very simple: the main thread main starts a sub-thread Worker, then lets the worker sleep for 500ms, while the main sleeps for 200ms, and then the main calls the interrupt method of the worker thread To interrupt the worker, print the interrupted status after the worker is interrupted. The following is the execution result:





Worker started. 
Main thread stopped. 
Worker IsInterrupted: false 
Worker stopped. 

Worker has been interrupted, but the isInterrupted() method actually returns false, why?


After searching around on stackoverflow, I found that some netizens mentioned: You can view the JavaDoc (or source code) of the method that throws InterruptedException, so I checked the documentation of the Thread.sleep method. The doc describes this InterruptedException exception as follows:



InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. 





Conclusion: The interrupt method is used to interrupt the thread, and the state of the thread calling this method will be set to the "interrupted" state. Note: Thread interrupts only set the thread's interrupt status bit, it does not stop the thread. So when a thread is in an interrupted state, if it is blocked by the wait, sleep and jion methods, the JVM will reset the thread's interrupt flag to false and throw an InterruptedException, and then the developer can interrupt the state. The essential function of "bit" is that the programmer captures the InterruptedException exception thrown by the jvm according to the try-catch function block to do various processing, such as how to exit the thread. In short, the function of interrupt is to require the user to monitor the state of the thread by himself. Bit and process it."



At the same time, it can be understood as follows:
Thread.currentThread().interrupt(); This is used to clear the interrupt status, so that the next time the Thread.interrupted() method is called, it will always return to true, because the interrupt The logo has been restored.
Calling isInterrupted() simply queries the interrupted state and does not modify the state.

interrupt() is used to set the interrupt status. Returning true indicates that the interrupt status was set rather than cleared. When we call such interruptible (throw InterruptedException) methods as sleep, wait, etc., once the method throws InterruptedException, the interrupt status of the thread currently calling the method will be automatically cleared by the jvm, that is, when we call the isInterrupted method of the thread yes returns false. If you want to keep the interrupted state, you can call the interrupt method again to set the interrupted state. The reason for this is that java's interrupt does not really interrupt the thread, but only sets the flag bit (interrupt bit) to notify the user. If you catch the interrupt exception, it means that the current thread has been interrupted and you don't need to keep the interrupt bit.
interrupted is a static method that returns the interrupted status of the current thread. For example, if the current thread is interrupted (no interrupt exception is thrown, otherwise the interrupted state will be cleared), and you call the interrupted method, it will return true the first time. Then, the interrupted state of the current thread is cleared internally by the method. The second call will return false. If you just keep calling isInterrupted, it will always return true unless the interrupted state of the intermediate thread is cleared by other operations.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327039863&siteId=291194637