Java thread interrupt

Java thread interrupt

What is a thread interrupt

​ An interrupt is an indication to a thread that it should stop what it is doing and do something else (usually end the thread). For example, 360 is performing anti-virus scanning. When we click "stop detection", it is a thread interrupt. How a thread responds to an interrupt request depends on the programmer. If the task that the thread needs to handle is very important, the thread can ignore the interrupt reminder. But generally, the method of corresponding interrupt is to terminate the thread.

Interrupt principle

​ Each Thread object has a boolean type status bit (not a field in the Thread class, which should be in the C + + source code) to indicate whether there is an interrupt request (the request can come from all threads, including the interrupted Thread itself). When a Thread executes some methods, it will always detect broken bits from time to time to see if there are interrupt requests. If there are, it will process them accordingly.

​ Java interrupt mechanism is a cooperative mechanism, that is, the interrupt cannot directly terminate another thread (just change the middle break), but the interrupted thread needs to handle the interrupt itself (it can be ignored or terminated).

Interrupt bit

Get interrupt bit status

There are two main methods:

  • One is the static method interrupted of Thread, which will detect whether the Thread has an interrupt request. If the interrupt bit is true, that is, the Thread has an interrupt request at present, the method will return true and reset the interrupt bit to the default value of false.
  • The other is the instance method of Thread object, isInterrupted. This method also detects whether the Thread has an interrupt request, which is the same as the interrupted method. But the difference is that isInterrupted does not change the state of the interrupt bit.

Change interrupt bit status

There are also two types:

  • Mainly through the instance method of Thread object: interrupt(). After calling this method, the interrupt bit of the Thread will be set to true, but it does not really interrupt the Thread.
  • You can also set the middle break to false through the interrupted() method.

Code implementation of interrupt

It can be divided into two categories: one is the interrupt when a thread calls a non blocking method, and the other is the interrupt when calling a blocking method. When a thread interrupts while executing a method, it will throw an InterruptedException exception and set the status bit to false.

An interrupt occurred while executing a non blocking method

public class InterruptTest01 {
    public static void main(String[] args) throws InterruptedException {
        Thread interruptThread = new Thread(()->{
            System.out.println("interruptThread Thread is running......");
            while (true) {
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("Interrupt signal detected, thread terminated");
                    // Or other treatment
                    return;
                }
            }
        }, "interruptThread");
        interruptThread.start();
        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName() + "Thread direction" + interruptThread.getName() + "The thread sends an interrupt signal....");
        interruptThread.interrupt();
    }
}

An interrupt occurred while executing the blocking method

package thread;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * @author: OnlyOne
 * @create: 2020-12-15 15:52
 * @description:
 **/
public class InterruptTest02 {
    public static void main(String[] args) throws InterruptedException {
        Thread interruptThread = new Thread(()->{
            try {
                while (true) {
                    System.out.println("interruptThread The thread is about to sleep for 5 seconds.....");
                    TimeUnit.SECONDS.sleep(5);
                }
            }catch (InterruptedException e) {
                    System.out.println("Capture InterruptedException Abnormal....");
                    System.out.println("At this time, the middle break position:" + Thread.currentThread().isInterrupted());
                    return;
                }
        }, "interruptThread");
        interruptThread.start();

        // The main thread sleeps for two seconds so that the interrupt thread sleeps
        TimeUnit.SECONDS.sleep(2);

        System.out.println(Thread.currentThread().getName() + "Thread direction" + interruptThread.getName() + "The thread sends an interrupt signal....");
        interruptThread.interrupt();
    }
}

In the above program, when the main thread sends an interrupt request to the interruptThread, the status bit of the interruptThread is set to true. However, at this time, the interruptThread thread is calling the blocking method, so an InterruptedException exception will be thrown.

reference resources

https://www.infoq.cn/article/java-interrupt-mechanism/

https://www.jianshu.com/p/a8abe097d4ed

https://ifeve.com/java-interrupt/

https://ifeve.com/thread-management-4/

Tags: Multithreading

Posted by JamieWAstin on Mon, 02 May 2022 02:59:29 +0300