当前位置:网站首页>Interview shock 26: how to stop threads correctly?

Interview shock 26: how to stop threads correctly?

2022-06-11 15:14:00 Wang Lei

stay Java The implementation methods of stopping threads in are as follows 3 Kind of :

  1. Custom interrupt identifier , Stop thread .
  2. Use thread interrupt method interrupt Stop thread .
  3. Use stop Stop thread .

among stop Method is @Deprecated Expiration method of decoration , That is, the deprecated expiration method , because stop Method will directly stop the thread , In this way, the thread is not given enough time to process the saved work before stopping , It will cause the problem of incomplete data , Therefore, it is not recommended to use . and There are also some problems with custom interrupt identification , So in general ,interrupt Method is the most ideal way 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
        }
    }
}

but The problem with customizing interrupt identifiers is : Thread interruption is not timely enough . Because the thread is executing , Unable to call while(!isInterrupt) To determine whether the thread is terminated , It can only determine whether to terminate the current thread at the next run , So it doesn't interrupt the thread in time , For example, 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  Then stop the thread
                System.out.println("thread  Execution steps 1: The thread is about to go to sleep ");
                try {
                    //  Sleep  1s
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread  Execution steps 2: The thread executes the task ");
            }
        });
        thread.start(); //  Start thread

        //  Sleep  100ms, wait for  thread  The thread runs
        Thread.sleep(100);
        System.out.println(" The main thread : An attempt was made to terminate the thread  thread");
        //  Modify interrupt identifier , Interrupt threads
        isInterrupt = true;
    }
}

The execution result of the above code is shown in the figure below : image.png What we expect is : The thread executes step 1 after , Received instruction to interrupt thread , Then don't perform any more steps 2 了 , However, it can be seen from the above implementation results , Using a custom interrupt identifier is not possible to achieve our expected results , This is the custom interrupt identifier , The problem of not responding in time .

2.interrupt Interrupt threads

Use interrupt Method can be given to the thread executing the task , Send an instruction to interrupt the thread , It does not interrupt the thread directly , Instead, it sends a signal to interrupt the thread , Leave the initiative of whether the thread is being interrupted to the coder . Compared with the custom interrupt identifier , It can receive interrupt instruction in time , 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  Execution steps 1: The thread is about to go to sleep ");
            try {
                //  Sleep  1s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("thread  Thread received interrupt instruction , Execute interrupt operation ");
                //  Interrupt the task execution of the current thread
                break;
            }
            System.out.println("thread  Execution steps 2: The thread executes the task ");
        }
    });
    thread.start(); //  Start thread

    //  Sleep  100ms, wait for  thread  The thread runs
    Thread.sleep(100);
    System.out.println(" The main thread : An attempt was made to terminate the thread  thread");
    //  Modify interrupt identifier , Interrupt threads
    thread.interrupt();
}

The execution result of the above code is shown in the figure below : image.png As can be seen from the above results , After the thread receives the interrupt instruction , Immediately interrupted the thread , Compared with the previous method of customizing interrupt identifier , It can respond to interrupt thread instructions in a more timely manner .

3.stop Stop thread

stop Method can stop the thread , But it is already an obsolete method that is not recommended , This can be done through Thread Class ,stop Source code is as follows : image.png As can be seen from the picture above ,stop The way is to be @Deprecated Modified deprecated expiration method , And the first sentence of the note shows stop The method is not safe . In the latest version Java in , This method has been removed directly , Therefore, it is strongly not recommended to use .

summary

This article introduces the method of stopping threads 3 Methods :

  1. Stop method of custom interrupt identifier , The disadvantage of this method is that it can not respond to the interrupt request in time ;
  2. Use interrupt Interrupt thread method , This method sends an interrupt signal to the thread , It can respond to interruptions in a timely manner , It is also the most recommended method ;
  3. And finally stop Method , Although it can also stop threads , But this method is outdated and not recommended , stay Java The latest version has been removed directly , So it's not recommended .

It's up to you to judge right and wrong , Disdain is to listen to people , Gain or loss is more important than number .

official account :Java Analysis of the real interview questions

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

原网站

版权声明
本文为[Wang Lei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012031268053.html