Interview assault 26: how to stop threads correctly?

There are three ways to stop threads in Java:

  1. Customize the interrupt identifier to stop the thread.
  2. Use the thread interrupt method interrupt to stop the thread.
  3. Use stop to stop the thread.

The stop method is an expiration method modified by @ Deprecated, that is, it is not recommended to use. Because the stop method will directly stop the thread, it will not give the thread enough time to process the saving work before stopping, which will cause the problem of incomplete data. Therefore, it is not recommended to use it. There are also some problems with custom interrupt identification, so overall, interrupt method is the most ideal method to stop threads. Next, let's look at their specific differences.

1. Custom interrupt identifier

Custom interrupt identifier is to define a variable in the program to determine whether the thread should interrupt execution. The specific implementation code is as follows:

class FlagThread extends Thread {
    // Custom interrupt identifier
    public volatile boolean isInterrupt = false;
    @Override
    public void run() {
        // If true - > interrupt execution
        while (!isInterrupt) {
            // Business logic processing
        }
    }
}

However, the problem with custom interrupt identifiers is that thread interrupts are not timely enough. Because the thread cannot call while(!isInterrupt) to judge whether the thread is in the termination state during execution, it can only judge whether to terminate the current thread during the next run, so it is not timely enough to interrupt the thread, such as the following code:

class InterruptFlag {
    // Custom interrupt identifier
    private static volatile boolean isInterrupt = false;

    public static void main(String[] args) throws InterruptedException {
        // Create interruptible thread instances
        Thread thread = new Thread(() -> {
            while (!isInterrupt) { // If isInterrupt=true, the thread is stopped
                System.out.println("thread Execute step 1: the thread is about to enter the sleep state");
                try {
                    // Sleep for 1s
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread Execute step 2: the thread executes the task");
            }
        });
        thread.start(); // Start thread

        // Sleep for 100ms and wait for the thread thread to run
        Thread.sleep(100);
        System.out.println("Main thread: an attempt was made to terminate the thread thread");
        // Modify the interrupt identifier to interrupt the thread
        isInterrupt = true;
    }
}

The execution result of the above code is shown in the following figure:

What we expect is that after the thread executes step 1, it receives the instruction to interrupt the thread, and then it will not execute step 2 again. However, from the above execution results, it can be seen that it is impossible to achieve our expected results by using the user-defined interrupt identifier, which is the problem that the response of the user-defined interrupt identifier is not timely enough.

2.interrupt interrupt thread

Using the interrupt method, you can send an instruction to interrupt the thread to the thread executing the task. It does not directly interrupt the thread, but sends a signal to interrupt the thread, and gives the initiative of whether the thread is being interrupted to the coder. Compared with the custom interrupt identifier, it can receive the interrupt instruction more timely, as shown in the following code:

public static void main(String[] args) throws InterruptedException {
    // Create interruptible thread instances
    Thread thread = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("thread Execute step 1: the thread is about to enter the sleep state");
            try {
                // Sleep for 1s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("thread The thread receives the interrupt instruction and executes the interrupt operation");
                // Interrupt the task execution of the current thread
                break;
            }
            System.out.println("thread Execute step 2: the thread executes the task");
        }
    });
    thread.start(); // Start thread

    // Sleep for 100ms and wait for the thread thread to run
    Thread.sleep(100);
    System.out.println("Main thread: an attempt was made to terminate the thread thread");
    // Modify the interrupt identifier to interrupt the thread
    thread.interrupt();
}

The execution result of the above code is shown in the following figure:

It can be seen from the above results that the thread immediately interrupts the thread after receiving the interrupt instruction. Compared with the previous method of customizing the interrupt identifier, it can respond to the interrupt thread instruction in a more timely manner.

3.stop thread

Although the stop method can stop the Thread, it is already an obsolete method that is not recommended. This can be found from the source code in the Thread class. The stop source code is as follows:

As can be seen from the above picture, the stop method is an expired method modified by @ Deprecated, which is not recommended. The first sentence of the comment indicates that the stop method is unsafe. In the latest version of Java, this method has been removed directly, so it is strongly not recommended.

summary

This article introduces three methods to stop threads:

  1. The stop method of user-defined interrupt identifier. The disadvantage of this method is that it can not respond to the interrupt request in time;
  2. Interrupt thread method is used. This method sends an interrupt signal to the thread, which can respond to the interrupt in time. It is also the most recommended method;
  3. The last is the stop method. Although it can also stop threads, this method is outdated and not recommended. It has been directly removed in the latest version of Java, so it is not recommended.

Right and wrong are judged by ourselves, bad reputation is heard by others, and the number of gains and losses is safe.

The official account: Java interview

Interview collection: https://gitee.com/mydb/interview

Keywords: Java Back-end

Added by Rob the R on Tue, 01 Mar 2022 02:49:51 +0200