[Java|Multithreading and high concurrency] Two methods of thread interruption

1 Introduction

Thread interruption refers to forcibly terminating the execution of a thread during its execution. Although it is interrupted, it is essentially to let the run method execute quickly, instead of halfway through the run method and force it to end.
This article mainly introduces two methods of thread interruption
insert image description here

2. Method 1: Custom flag

Take a look at the following code:

public class Demo6 {
    
    
    private static boolean flag = false;
    public static void main(String[] args) {
    
    
        Thread t = new Thread(()->{
    
    
            while(!flag){
    
    
                System.out.println("线程执行中!");
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
            System.out.println("线程执行完了!");
        });
        t.start();

        try {
    
    
            Thread.sleep(3000);
        } catch (InterruptedException e) {
    
    
            throw new RuntimeException(e);
        }
        System.out.println("设置标志位,让线程执行结束");
        flag = true;
    }
}

Running results:
insert image description here
Look at the picture below: In this code, a flag bit
insert image description here
is defined , and the flag bit is used as the execution condition of the method, and "thread execution" is output every 1s, and then the thread (main Thread) sleeps for 3s, after 3s, the thread starts to execute, output "set the flag, let the thread execution end", and modify the value of the variable , the thread does not meet the execution conditions, so the thread execution is completed.flag线程trunmainmainflagfalsett

3. Method 2: Use the flags that come with the standard library

Java provides a mechanism for interrupting a thread, that is, calling a thread's interrupt()method.
When a thread is interrupted, it receives an interrupt signal, but that doesn't mean the thread stops executing immediately. A thread can decide whether to stop executing by checking its own interrupt status. A thread can isInterrupted()check whether it has been interrupted by calling a method. This method returns true if the thread has been interrupted, otherwise returns false.

Example:

public class Demo7 {
    
    
    public static void main(String[] args) {
    
    
        Thread t = new Thread(()->{
    
    
            while(!Thread.currentThread().isInterrupted()){
    
    
                System.out.println("线程执行中!");
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
            System.out.println("线程执行完了!");
        });
        t.start();

        try {
    
    
            Thread.sleep(3000);
        } catch (InterruptedException e) {
    
    
            throw new RuntimeException(e);
        }
        System.out.println("设置标志位,让线程执行结束");
        t.interrupt();
    }
}

insert image description here
But if you write this way, there will be problems
insert image description here
. You can see that an exception is thrown here. And although the flag bit is set, the thread does not end.
Note that interruptthe method has two behaviors:

  1. If the thread is in a normal state, the flag will be set to true
  2. InterruptedExceptionIf the thread is blocked (sleep), the flag will not be set, but an exception will be triggered , which will wake up early. Since I just printed the log here and did not end the loop, the thread is sleepstill catchin execution

If you want to end the loop, you can catchaddbreak
insert image description here

4. Summary

The thread interruption mechanism is an elegant way to stop the thread, which can prevent the thread from waiting for a certain condition indefinitely and cause the program to appear deadlock or unresponsive. However, thread interruption is not a method to forcibly terminate the thread, it requires the thread itself to determine whether to stop execution. Therefore, when writing a thread, you need to pay attention to checking the interrupt status of the thread at an appropriate time and make corresponding processing.
insert image description here

Thank you for watching! I hope this article can help you!
Column: "Java Learning Journey from Scratch" is constantly being updated, welcome to subscribe!
"Wish to encourage you and work together!"
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/131086529