03-Thread--interrupt mechanism

Interrupt mechanism in java


Read material one: https://www.cnblogs.com/hapjin/p/5450779.html

Reading material two: https://www.ibm.com/developerworks/cn/java/j-jtp05236.html

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        super.run();
        try{
    
    
            for (int i = 0; i < 500000; i++) {
    
    
                if (this.interrupted()) {
    
    
                    System.out.println("should be stopped and exit");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
            System.out.println("this line cannot be executed. cause thread throws exception");//这行语句不会被执行!!!
        }catch(InterruptedException e){
    
    
            System.out.println("catch interrupted exception");
            e.printStackTrace();
        }
    }
}

When the MyThread thread detects that the interrupt flag is true, it throws InterruptedException on line 9. In this way, the thread can no longer execute other normal statements (for example, the statement on line 13 will not be executed). This shows that the interrupt() method has two functions, one is to set the interrupted status of the thread (the interrupted status changes from false to true); the other is to let the interrupted thread throw InterruptedException.

This is very important. In this way, for those blocking methods (such as wait() and sleep()), when another thread calls interrupt() to interrupt the thread, the thread will exit from the blocked state and throw an interrupt exception. In this way, we can catch the interrupt exception and perform some processing on the abnormal exit of the thread from the blocking method according to the actual situation.

For example: Thread A has acquired the lock and entered the synchronization code block, but it is blocked by calling the wait() method due to insufficient conditions. At this time, thread B executes threadA.interrupt() to request interruption of thread A. At this time, thread A will throw InterruptedException, we can catch this exception in catch and deal with it accordingly (for example, throw it further up)

Guess you like

Origin blog.csdn.net/qq_41729287/article/details/113888131