Java Multithread interrupt - thread interrupt

Keywords: Java

As the word "interrupt" means, interrupt it in the middle of thread running (run method). In Java, there are three methods about thread interrupt

//Interrupt thread (instance method)
public void Thread.interrupt();

//Determine whether the thread is interrupted (instance method)
public boolean Thread.isInterrupted();

//Judge whether it is interrupted and clear the current interrupt state (static method)
public static boolean Thread.interrupted();

When a thread is in a blocked state or trying to perform a blocking operation, use Thread.interrupt() to interrupt the thread. Note that an exception of InterruptedException will be thrown at this time, and the interrupt state will be reset (from the interrupt state to the non interrupt state). The following code will demonstrate the process:

package com.lxk.thread.Interrupt;

import java.util.concurrent.TimeUnit;

/**
 * Blocking interrupt
 * <p>
 * When a thread is blocked or trying to perform a blocking operation, use Thread.interrupt() to interrupt the thread,
 * Note that an exception of InterruptedException will be thrown and the interrupt status will be reset (from interrupt status to non interrupt status)
 *
 * @author LiXuekai on 2020/4/30
 */
public class InterruptThread1 {


    /**
     * Blocking interrupt
     */
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                //while in try, you can exit the run cycle through an exception interrupt
                try {
                    while (true) {
                        //The current thread is blocked. Exceptions must be caught and cannot be thrown out
                        TimeUnit.SECONDS.sleep(2);
                    }
                } catch (InterruptedException e) {
                    System.out.println("interrupted When Sleep");
                    boolean interrupt = this.isInterrupted();
                    //Interrupt status reset
                    System.out.println("interrupt:" + interrupt);
                }
            }
        };
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        //Interrupt a blocked thread
        t1.interrupt();

        /*
         * Output results:
         interrupted When Sleep
         interrupt:false
         */
    }
}

As shown in the above code, we create a thread and call the sleep method in the thread, thus using thread to enter the blocking state. After starting the thread, we call the interrupt method of the thread instance object to interrupt the blocking exception and throw the InterruptedException exception. At this time, the interrupt state will also be reset. Some people here may wonder why Thread.sleep(2000) is not used; instead, TimeUnit.SECONDS.sleep(2) is used. In fact, the reason is very simple. The former does not have a clear unit description when it is used, while the latter expresses the unit of seconds very clearly. In fact, the internal implementation of the latter finally calls Thread.sleep(2000); In order to write code with clearer semantics, it is recommended to use TimeUnit.SECONDS.sleep(2); note that TimeUnit is an enumeration type. ok ~, in addition to the blocking interrupt scenario, we may also encounter threads in the running and non blocking state. In this case, directly calling Thread.interrupt() to interrupt a thread will not get any response. The following code will not interrupt a thread in the non blocking state:

package com.lxk.thread.Interrupt;

import java.util.concurrent.TimeUnit;

/**
 * Threads in a running and non blocking state
 * Calling Thread.interrupt() directly to interrupt a thread will not get any response
 *
 * @author LiXuekai on 2020/4/30
 */
public class InterruptThread2 {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("Not interrupted");
                }
            }
        };
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        t1.interrupt();

        /*
         * Output results (infinite execution):
         Not interrupted
         Not interrupted
         Not interrupted
         ......
         */

        // Although we called the interrupt method, thread t1 was not interrupted, because a thread in a non blocking state requires us to manually detect the interrupt and terminate the program
    }
}

The improved code is as follows:

package com.lxk.thread.Interrupt;

import java.util.concurrent.TimeUnit;

/**
 * When the thread is running, we can also call the instance method interrupt() to interrupt the thread,
 * But at the same time, we must judge the interrupt state manually and write the code of the interrupt thread (in fact, the code to end the run method body)
 * @author LiXuekai on 2020/4/30
 */
public class InterruptThread3 {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    //Determine whether the current thread is interrupted
                    if (this.isInterrupted()) {
                        System.out.println("Thread interrupt");
                        break;
                    }
                }

                System.out.println("Out of loop,Thread interrupt!");
            }
        };
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        t1.interrupt();

        /*
         * Output results:
         Thread interrupt
         Out of loop, thread interrupted!
         */
    }
}

Yes, we use the instance method isInterrupted in our code to determine whether the thread has been interrupted. If interrupted, we will jump out of the loop to end the thread. Note that the non blocking state call interrupt() will not cause the interrupt state to reset.

In summary, we can briefly summarize two situations of interruption. One is that when a thread is in a blocking state or trying to perform a blocking operation, we can use the instance method interrupt() to interrupt the thread. After the interrupt operation is performed, an interrupt exception will be thrown (the exception must be caught and cannot be thrown out) and the interrupt state will be reset. The other is when a thread is in a blocking state or trying to perform a blocking operation In the running state, we can also call the instance method interrupt() to interrupt the thread, but at the same time, we must judge the interrupt state manually, and write the code to interrupt the thread (in fact, the code to end the run method body). Sometimes we may need to consider the above two situations when coding, so we can write as follows:

package com.lxk.thread.Interrupt;

import java.util.concurrent.TimeUnit;

/**
 * One is that when a thread is in a blocking state or trying to perform a blocking operation, we can use the instance method interrupt() to interrupt the thread. After the interrupt operation is performed, an interruptException will be thrown (the exception must be caught and cannot be thrown out) and the interrupt state will be reset,
 * The other is that when the thread is running, we can also call the instance method interrupt() to interrupt the thread, but at the same time, we must judge the interrupt state manually and write the code to interrupt the thread (in fact, the code to end the run method body).
 * Sometimes we may need to consider the above two situations when coding, so we can write as follows
 *
 * @author LiXuekai on 2020/4/30
 */
public class InterruptThread4 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    //Judge whether the current thread has been interrupted. Note that the interrupted method is static and will reset the interrupt state after execution
                    while (!Thread.interrupted()) {
                        TimeUnit.SECONDS.sleep(2);
                    }
                } catch (InterruptedException e) {
                    System.out.println(e);
                }
            }
        };
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        t1.interrupt();

        /*
         * Output results:
         java.lang.InterruptedException: sleep interrupted
         */
    }
}

Java thread interrupt! =stop thread

Posted by sheila on Fri, 08 May 2020 22:53:04 -0700