too difficult! The interviewer actually wants me to stop a running thread?

Stopping a thread means stopping the operation that is being done before the task is finished processing, that is, abandoning the current operation. You can use the Thread.stop() method to stop a thread, but it is best not to use it. Although it can indeed stop a running thread, this method is unsafe and has been deprecated.

There are three ways to terminate a running thread in java:

Use the exit flag to make the thread exit normally, that is, the thread terminates when the run method is completed.
Use the stop method to force termination, but this method is not recommended, because stop, like suspend and resume, is an expired method.
Use the interrupt method to interrupt the thread.

Unstoppable thread

The effect of the interrupt() method is not like the for+break statement, which immediately stops the loop. Calling the interrupt method is to hit a stop sign in the current thread, not really stopping the thread. Insert picture description here
Output result:Insert picture description here

Determine whether the thread is stopped

"2020 the latest Java basics and detailed video tutorials and learning routes!
Two methods are provided in the Thread.java class:

this.interrupted(): test whether the current thread has been interrupted;
this.isInterrupted(): test whether the thread has been interrupted;
then what is the difference between these two methods?

Let's take a look at the explanation of this.interrupted() method: test whether the current thread has been interrupted, the current thread refers to the thread running this.interrupted() method.
Insert picture description here
operation result:

??
 ??
复制代码

Although the class Run.java calls the following code on the thread object: thread.interrupt(), which is used later

(" 1??" + ());
(" 2??" + ());
复制代码

To determine whether the thread represented by the thread object is stopped, but from the results printed on the console, the thread has not stopped, which also proves the explanation of the interrupted() method to test whether the current thread has been interrupted. This current thread is main, it has never been interrupted, so the printed result is two false.

How to make the main thread produce an interrupt effect?
Insert picture description here
The running effect is:

??
 ??
复制代码

The method interrupted() does determine whether the current thread is stopped. But why is the second Boolean value false? The explanation of the interrupted method in the official help document:

Test whether the current thread has been interrupted. The interruption status of the thread is cleared by this method.

In other words, if the method is called twice in a row, the second call returns false.

Let's look at the inInterrupted() method.

Insert picture description here
operation result:

??
??
Copy the code
isInterrupted() and clear the state, so two true are printed.

Threads that can be stopped-exception method

With the knowledge points learned before, you can use the for statement in the thread to determine whether the thread is in a stopped state. If it is in a stopped state, then the following code can no longer run:
Insert picture description here
operation result:Insert picture description here

Although the above example stops the thread, if there are statements below the for statement, it will continue to run. Look at the following example: Insert picture description here
The result of using Run.java is: Insert picture description here
How to solve the problem of continuing to run the statement? Take a look at the updated code:
Insert picture description here
the results of using Run.java are as follows:

Insert picture description here
Stop in deep sleep

What is the effect if the thread stops the thread in sleep() state? Insert picture description here
The result of running with Run.java is: Insert picture description here
judging from the printed result, if a thread is stopped in the sleep state, it will enter the catch statement and clear the stop state value to make it false.

The previous experiment was to sleep first and then interrupt() to stop. The opposite operation should be paid attention to during the learning process:

Insert picture description here
Operation result: Insert picture description here
thread that can be stopped-brute force stop

Using the stop() method to stop the thread is very violent. Insert picture description here
Operation results: Insert picture description here
6. Method stop() and java.lang.ThreadDeath exceptions When
calling the stop() method, java.lang.ThreadDeath exceptions will be thrown, but normally, this exception does not need to be captured explicitly.

Insert picture description here
The stop() method is obsolete, because if the thread is forced to stop, some clean-up work may not be completed. Another situation is that the locked object is unlocked, causing the data to not be synchronized, and the problem of data inconsistency occurs.

Undesirable consequences of releasing the lock

Using stop() to release the lock will cause data inconsistency. If such a situation occurs, the data processed by the program may be damaged, which will eventually lead to an error in the process of program execution. Special attention must be paid to:

public class SynchronizedObject {
    
        private String name = "a";    private String password = "aa";    public synchronized void printString(String name, String password){
    
            try {
    
                this.name = name;            Thread.sleep(100000);            this.password = password;        } catch (InterruptedException e) {
    
                e.printStackTrace();        }    }    public String getName() {
    
            return name;    }    public void setName(String name) {
    
            this.name = name;    }    public String getPassword() {
    
            return password;    }    public void setPassword(String password) {
    
            this.password = password;    }}public class MyThread extends Thread {
    
        private SynchronizedObject synchronizedObject;    public MyThread(SynchronizedObject synchronizedObject){
    
            this.synchronizedObject = synchronizedObject;    }    public void run(){
    
            synchronizedObject.printString("b", "bb");    }}public class Run {
    
        public static void main(String args[]) throws InterruptedException {
    
            SynchronizedObject synchronizedObject = new SynchronizedObject();        Thread thread = new MyThread(synchronizedObject);        thread.start();        Thread.sleep(500);        thread.stop();        System.out.println(synchronizedObject.getName() + "  " + synchronizedObject.getPassword());    }}
复制代码

Output result:

b  aa
复制代码

Because the stop() method and the method marked as "expired/obsolete" in the JDK, it is obviously functionally flawed, so it is not recommended to use the stop() method in the program.

Use return to stop the thread

The method interrupt() combined with return can also achieve the effect of stopping the thread:

public class MyThread extends Thread {
    
        public void run(){
    
            while (true){
    
                if(this.isInterrupted()){
    
                    System.out.println("线程被停止了!");                return;            }            System.out.println("Time: " + System.currentTimeMillis());        }    }}public class Run {
    
        public static void main(String args[]) throws InterruptedException {
    
            Thread thread = new MyThread();        thread.start();        Thread.sleep(2000);        thread.interrupt();    }}
复制代码

Output result:

...Time: 1467072288503Time: 1467072288503Time: 1467072288503线程被停止了!
复制代码

However, it is recommended to use the "throwing exception" method to stop the thread, because the exception can also be thrown up in the catch block, so that the thread stop event can be propagated.

Original link: https://juejin.cn/post/6906365708230197261

Guess you like

Origin blog.csdn.net/weixin_46699878/article/details/111215939