How to stop a running thread

Personal blog visit http://www.x0100.top 

Stopping a thread means stopping the operation before the task finishes processing, that is, giving up the current operation. To stop a thread, you can use the Thread.stop() method, but you'd better not use it. Although it does stop a running thread, this method is not safe and has been abandoned.

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

  1. Use the exit flag to make the thread exit normally, that is, when the run method is completed, the thread terminates.

  2. Stop method is used to forcibly terminate, but this method is not recommended, because stop, like suspend and resume, is an expired and obsolete method.

  3. Interrupt the thread using the interrupt method.

     

1. Thread that cannot be stopped

The interrupt() method doesn't work as well as the for+break statement, stopping the loop immediately. The interrupt method is called with a stop flag in the current thread. It is not true to stop the thread.

 {
    {
        .run();
        ( i=; i<; i++){
            System.out.println(+(i+));
        }
    }
}

 {
    {
        Thread thread =  MyThread();
        thread.start();
         {
            Thread.sleep();
            thread.interrupt();
        }  (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output results:

...
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000

 

2. Judge whether the thread is stopped

Two methods are provided in the Thread.java class:

  1. this.interrupted(): test whether the current thread has been interrupted;

  2. this.isInterrupted(): test whether the thread has been interrupted;

What are the differences between the two methods?

Let's first 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.

 {
    {
        .run();
        ( i=; i<; i++){
            i++;

        }
    }
}

 {
    {
        Thread thread =  MyThread();
        thread.start();
         {
            Thread.sleep();
            thread.interrupt();

            System.out.println( + thread.interrupted());
            System.out.println( + thread.interrupted());
        }  (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Operation result:

 ??
 ??

In the Run.java class, although the following code is called on the thread object: thread.interrupt(), it is used later

(" 1??" + ());
(" 2??" + ());

To determine whether the thread represented by the thread object is stopped, but from the results printed by the console, the thread is not stopped, which also proves the interpretation of the interrupted() method, and tests whether the current thread has been interrupted. The current thread is main, which has never been interrupted, so the result of printing is two false

How to interrupt the main thread?

   {
    {
        Thread.currentThread().interrupt();
        System..println( + Thread.interrupted());
        System..println( + Thread.interrupted());

        System..println();
    }
}

The operation effect is:

 ??
 ??

Method interrupted() does determine whether the current thread is in a stopped state. But why is the second Boolean false? Explanation of the interrupted method in the official help document:

Test whether the current thread has been interrupted. The thread's interrupt state is cleared by this method.

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

Let's take a look at the inInterrupted() method.

   {
    {
        Thread thread =  MyThread();
        thread.start();
        thread.interrupt();
        System..println( + thread.isInterrupted());
        System..println( + thread.isInterrupted());
    }
}

Operation result:

 ??
 ??

isInterrupted() and is in the clear state, so two true are printed.

 

3. Thread 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 the stop state. If it is in the stop state, the following code will no longer run:

 {
    {
        .run();
        ( i=; i<; i++){
            (.interrupted()) {
                System.out.println();
                ;
            }
            System.out.println(+(i+));
        }
    }
}

 {
    {
        Thread thread =  MyThread();
        thread.start();
         {
            Thread.sleep();
            thread.interrupt();
        }  (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Operation result:

...
i=202053
i=202054
i=202055
i=202056
 Thread terminated, for loop no longer executed

Although the above example stops the thread, if there is a statement under the for statement, it will continue to run. Consider the following example:

public {
    public void run(){
        .run();
        (int i=; i<; i++){
            (.interrupted()) {
                .out.println();
                ;
            }
            .out.println(+(i+));
        }

        .out.println();
    }
}

The result of using Run.java is:

...
i=180136
i=180137
i=180138
i=180139
 Thread terminated, for loop no longer executed
 This is a statement outside the for loop, which will also be executed

How to solve the problem of statement running? Take a look at the updated code:

public {
    public void run(){
        .run();
         {
            (int i=; i<; i++){
                (.interrupted()) {
                    .out.println();
                          ();
                }
                .out.println(+(i+));
            }

            .out.println();
        }  ( e) {
            .out.println();
            e.printStackTrace();
        }
    }
}

The results of running with Run.java are as follows:

...
i=203798
i=203799
i=203800
 Thread terminated, for loop no longer executed
 Enter the catch in MyThread.java class...
java.lang.InterruptedException
    at thread.MyThread.run(MyThread.java:13)

 

4. Stop in deep sleep

What is the effect if a thread stops in the sleep() state?

public {
    public void run(){
        .run();

         {
            .out.println();
            .sleep();
            .out.println();
        }  ( e) {
            .out.println( + .isInterrupted());
            e.printStackTrace();
        }

    }
}

The result of running with Run.java is:

Thread start...
When it is stopped, entered and called () method in deep sleep, the result is:
:  
     ( )
     (

From the printed results, if a thread is stopped in the sleep state, it will enter the catch statement and clear the stop state value to false.

The former experiment is to sleep first and then stop with interrupt(). In the process of learning, the opposite operation should also be noted:

     {
    {
        super.run();
         {
            System..println();
            ( i=; i<; i++){
                System..println( + i);
            }
            Thread.sleep();
            System..println();
        }  (InterruptedException e) {
             System..println();
            e.printStackTrace();
        }

    }
}

   {
    {
        Thread thread =  MyThread();
        thread.start();
        thread.interrupt();
    }
}

Operation result:

i=9998
i=9999
 Stop first, then encounter sleep, enter catch exception

    at java.lang.Thread.sleep(Native Method)
    at thread.MyThread.run(MyThread.java:15)

 

5. Thread that can stop - violent stop

Using the stop() method to stop a thread is very violent.

 {
      i = ;
    {
        .run();
         {
             (){
                System.out.println( + i);
                i++;
                Thread.sleep();
            }
        }  (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 {
    {
        Thread thread =  MyThread();
        thread.start();
        Thread.sleep();
        thread.stop();
    }
}

Operation result:

i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9

Process finished with exit code 0

 

6. Method stop() and java.lang.threadeath exceptions

Calling the stop() method throws a Java. Lang. threadeath exception, but usually this exception does not need to be caught explicitly.

 {
      i = ;
    {
        .run();
         {
            .stop();
        }  (ThreadDeath e) {
            System.out.println();
            e.printStackTrace();
        }
    }
}

 {
    {
        Thread thread =  MyThread();
        thread.start();
    }
}

stop() method and void, because forcing a thread to stop may cause some cleanup work to be incomplete. Another situation is that the locked object is unlocked, resulting in the data can not be synchronized processing, resulting in data inconsistency.

 

7. Bad consequences of releasing lock

Using stop() to release the lock will result in inconsistent data. If such a situation occurs, the data processed by the program may be damaged, which eventually leads to the process error 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 results:

b  aa

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

 

8. Use return to stop the thread

Using the method interrupt() in combination with return can also achieve the effect of thread stopping:

public class MyThread extends Thread {    public void run(){        while (true){            if(this.isInterrupted()){                System.out.println("Thread stopped!");                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 results:

... Time: 1467072288503Time: 1467072288503Time: 1467072288503 thread stopped!

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

340 original articles published, 230 praised, 460000 visitors+
His message board follow

Tags: Java JDK

Posted on Thu, 12 Mar 2020 23:43:01 -0700 by mofm