JAVA Concurrent Programming -- thread interrupt mechanism and interrupt()

Posted by yepster123 on Mon, 27 Dec 2021 09:03:19 +0100

1. What is a thread interrupt

2. API methods related to interrupts

3. Implement thread interrupt through a volatile variable

4. It is implemented through the interrupt api method of Thread class

5. If the interrupt flag of the current thread is true, will it stop immediately?

6. Static method thread Introduction to interrupted()

7. Summary

1. What is a thread interrupt
We all know that it is easy to start a thread in JAVA, and we all stop after the thread ends, but will we have such a situation that when the thread runs half way, we artificially stop the thread running half way? This is what we want to talk about today, thread interrupt mechanism.

Click thread Java source code, we found that there are stop, suspend, resume and other methods, but these methods have been abandoned, so they can't be used.

In current multi-threaded programming, a thread should not be forcibly interrupted or stopped by other threads, but should be stopped by the thread itself, so the above methods are abandoned.

In JAVA, there is no way to stop a thread immediately, but stopping a thread is particularly important, such as canceling a very time-consuming operation, so JAVA provides a mechanism to stop a thread - interrupt.

Interrupt is just a cooperation mechanism. JAVA does not add any syntax to interrupt. The interrupt process needs to be implemented by programmers themselves.

To interrupt a thread, you need to manually call the interrupt method of the thread, which only sets the interrupt ID of the thread object to true;

Then you need to write your own code to constantly detect the flag bit of the current thread. If it is true, the identified thread requires this thread to be interrupted. What to do at this time needs to be realized by writing your own code.

Each thread object has an identifier to identify whether the thread is interrupted:
The flag true indicates interrupt, and false indicates no interrupt;

By calling the thread object's interrupt method, it sets the label bit of the thread to true, which can be invoked in other threads or in its own thread.

2. API methods related to interrupts

//The instance method interrupt() only sets the interrupt flag bit of the thread to true and does not stop the thread
public void interrupt();

//This method does two things
//1. Return the interrupt status of the current thread
//2. Set the interrupt status of the current thread to true
public static boolean interrupted();

//Determine whether the current thread is interrupted
public boolean isInterrupted()

3. Implement thread interrupt through a volatile variable

public class InterruptDemo {
    //This is an interrupt flag bit
    private static volatile boolean isStop = false;

    public static void main(String[] args) {
        //Start a thread and cycle all the time. If the interrupt flag bit is changed to true by other threads, the execution of the thread will be stopped
        new Thread(() -> {
            while (true) {
                if (isStop) {
                    System.out.println(Thread.currentThread().getName() + "thread ------isStop = true,I quit");
                    break;
                }
                System.out.println("-------hello interrupt");
            }
        }, "t1").start();

        //Pause the thread for a few seconds
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        isStop = true;
    }

}

4. It is implemented through the interrupt api method of Thread class

public class InterruptDemo2 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while(true){
                System.out.println("The thread is running");
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("Thread interrupted isInterrupted:  " + Thread.currentThread().isInterrupted());
                    break;
                }
            }
        }, "t1");
        t1.start();

        //Active state, t1 thread is still executing
        try {
            TimeUnit.MILLISECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Interrupt thread
        t1.interrupt();
        //Let the thread jump out of the loop program
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

5. If the interrupt flag of the current thread is true, will it stop immediately?
From the above two cases, it can be seen that interrupt is just a collaborative mechanism, and modifying the interrupt identification bit is just that, rather than science stop interrupt.

6. Static method thread Introduction to interrupted()

This method has two main functions:
1) Judge whether the current thread is interrupted and return this flag bit (that is, return the interrupt status of the current thread)
2) Clears the interrupt state of the current thread

    public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "---" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + "---" + Thread.interrupted());
        System.out.println("111111");
        Thread.currentThread().interrupt();
        System.out.println("222222");
        System.out.println(Thread.currentThread().getName() + "---" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + "---" + Thread.interrupted());
    }

The returned result is:

As you can see,

When the interrupt() method has not been called:
The current thread interrupt status returned by calling interrupted() is false (not interrupted).

After the interrupt() method is called:
The first call to interrupted() returns the current interrupt status as (true), and clears the interrupt status of the current thread from true to false.
The second call to interrupted() returns that the current interrupt state is (false). Because the interrupt state of the current thread is false, the state does not change.

7. Summary

1) Interrupt is just a coordination mechanism. Modifying the interrupt identification bit is all, not stop interrupt immediately
2) Manually call the interrupt method of the thread, which only sets the interrupt ID of the thread object to true
3) You need to write your own code to constantly detect the flag bit of the current thread. If it is true, the identified thread requires this thread to be interrupted. What to do at this time requires you to write your own code.
4) Two consecutive calls to interrupted() may return different results

Topics: Java Multithreading