Detailed Explanation of Several Ways of High Concurrent Thread Interruption in java

  • 2021-12-04 18:42:20
  • OfStack

Directory controls thread interrupts through 1 variable. How to interrupt in thread blocking state through thread's own interrupt flag? Summarize

Control thread interrupt through 1 variable

Code:


package com.itsoku.chat05;	
import java.util.concurrent.TimeUnit;	
/**	
 *  WeChat official account: Passer-by A Java , focus on java Technology sharing (take you around   Crawler, distributed transactions, asynchronous message service, task scheduling, sub-database sub-table, big data, etc.), like please pay attention! 	
 */	
public class Demo1 {	
    public volatile static boolean exit = false;	
    public static class T extends Thread {	
        @Override	
        public void run() {	
            while (true) {	
                // Circular processing service 	
                if (exit) {	
                    break;	
                }	
            }	
        }	
    }	
    public static void setExit() {	
        exit = true;	
    }	
    public static void main(String[] args) throws InterruptedException {	
        T t = new T();	
        t.start();	
        TimeUnit.SECONDS.sleep(3);	
        setExit();	
    }	
}

A thread is started in the code, and there is an infinite loop in the run method of the thread, and the value of exit variable is used to control whether to exit or not. TimeUnit. SECONDS. sleep (3); Let the main thread sleep for 3 seconds. Why use TimeUnit here? TimeUnit is more convenient to use, and can clearly control the sleep time. The bottom layer is still converted to Thread. sleep. The program has a key: volatile keyword, exit variable must pass this modification, if this is removed, the program can not exit normally. volatile controls the visibility of variables in multithreaded settings, as described in previous articles on volatile, and will not be covered here.

Controlled by the interrupt flag of the thread

Sample code:


package com.itsoku.chat05;	
import java.util.concurrent.TimeUnit;	
/**	
 *  WeChat official account: Passer-by A Java , focus on java Technology sharing (take you around   Crawler, distributed transactions, asynchronous message service, task scheduling, sub-database sub-table, big data, etc.), like please pay attention! 	
 */	
public class Demo2 {	
    public static class T extends Thread {	
        @Override	
        public void run() {	
            while (true) {	
                // Circular processing service 	
                if (this.isInterrupted()) {	
                    break;	
                }	
            }	
        }	
    }	
    public static void main(String[] args) throws InterruptedException {	
        T t = new T();	
        t.start();	
        TimeUnit.SECONDS.sleep(3);	
        t.interrupt();	
    }	
}

Run the above program, and the program can end normally. There is an interrupt flag inside the thread. When the thread's interrupt () instance method is called, the thread's interrupt flag will be set to true, and the thread's interrupt flag can be obtained through the thread's instance method isInterrupted ().

How to interrupt a thread in a blocked state.

Sample code:


package com.itsoku.chat05;	
import java.util.concurrent.TimeUnit;	
/**	
 *  WeChat official account: Passer-by A Java , focus on java Technology sharing (take you around   Crawler, distributed transactions, asynchronous message service, task scheduling, sub-database sub-table, big data, etc.), like please pay attention! 	
 */	
public class Demo3 {	
    public static class T extends Thread {	
        @Override	
        public void run() {	
            while (true) {	
                // Circular processing service 	
                // The following simulates the blocking code 	
                try {	
                    TimeUnit.SECONDS.sleep(1000);	
                } catch (InterruptedException e) {	
                    e.printStackTrace();	
                }	
            }	
        }	
    }	
    public static void main(String[] args) throws InterruptedException {	
        T t = new T();	
        t.start();	
    }	
}

Run the above code and find that the program cannot end.

I would like to add a few points of knowledge here:

1. Call the thread's interrupt () instance method, and the thread's interrupt flag is set to true

2. When a thread is in a blocking state, call the thread's interrupt () instance method, an InterruptedException exception will be triggered inside the thread, and the interrupt flag inside the thread will be cleared (that is, the interrupt flag will be set to false)

Then the above code can call the thread's interrupt () method to throw an InterruptedException exception to interrupt the blocking caused by the sleep method. Adjust the code under 1 as follows:


package com.itsoku.chat05;	
import java.util.concurrent.TimeUnit;	
/**	
 *  WeChat official account: Passer-by A Java , focus on java Technology sharing (take you around   Crawler, distributed transactions, asynchronous message service, task scheduling, sub-database sub-table, big data, etc.), like please pay attention! 	
 */	
public class Demo3 {	
    public static class T extends Thread {	
        @Override	
        public void run() {	
            while (true) {	
                // Circular processing service 	
                // The following simulates the blocking code 	
                try {	
                    TimeUnit.SECONDS.sleep(1000);	
                } catch (InterruptedException e) {	
                    e.printStackTrace();	
                    this.interrupt();	
                }	
                if (this.isInterrupted()) {	
                    break;	
                }	
            }	
        }	
    }	
    public static void main(String[] args) throws InterruptedException {	
        T t = new T();	
        t.start();	
        TimeUnit.SECONDS.sleep(3);	
        t.interrupt();	
    }	
}

Run results:


java.lang.InterruptedException: sleep interrupted	
    at java.lang.Thread.sleep(Native Method)	
    at java.lang.Thread.sleep(Thread.java:340)	
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)	
    at com.itsoku.chat05.Demo3$T.run(Demo3.java:17)

The program can end normally, analyze the above code under 1, and pay attention to several points:

1. When the t. interrupt () method is called in the main method, the interrupt flag inside the thread t is set to true

2. Then the InterruptedException exception inside the run () method will be triggered, so there is an exception output in the running result. As mentioned above, when the trigger InterruptedException In case of exception, the interrupt flag inside the thread will be cleared again (changed to false), so this. interrupt () is called again in catch; 1 time, set the interrupt flag to false

3. In the run () method, this. isInterrupted () is used to get the interrupt flag of the thread and exit the loop (break)

Summarize

When a thread is in a blocked state or attempting to perform a blocking operation, you can use Thread. interrupt () to interrupt the thread. Note that an InterruptedException exception will be thrown and the interrupt state will be reset (from interrupt state to non-interrupt state)

There is a loop body inside, and one variable can be used as a signal to control whether the thread is interrupted or not. Note that the variable needs volatile modification

Several methods in this paper can be combined to flexibly use interrupts of control threads

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: