Preface
Stopping a thread means stopping the operation being done before the task has finished processing the task, that is, giving up the current operation. You can use the() method to stop a thread, but it is best not to use it. Although it does stop a running thread, this method is unsafe and is a discarded method. 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 terminate, but this method is not recommended, because stop, like suspend and resume, are expired and invalid methods.
- Use the interrupt method to interrupt the thread.
1. Unstoppable threads
The interrupt() method does not use the effect of the for+break statement, and the loop will be stopped immediately. Calling the interrupt method is to type a stop flag in the current thread, and it does not really stop the thread.
public class MyThread extends Thread { public void run(){ (); for(int i=0; i<500000; i++){ ("i="+(i+1)); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); (); try { (2000); (); } catch (InterruptedException e) { (); } } }
Output result:
... i=499994 i=499995 i=499996 i=499997 i=499998 i=499999 i=500000
2. Determine whether the thread is stopped
There are two methods provided in the class:
- (): Test whether the current thread has been interrupted;
- (): Test whether the thread has been interrupted;
So what is the difference between these two methods?
Let's first look at the explanation of the() method: test whether the current thread has been interrupted. The current thread refers to the thread running the() method.
public class MyThread extends Thread { public void run(){ (); for(int i=0; i<500000; i++){ i++; // ("i="+(i+1)); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); (); try { (2000); (); ("stop 1??" + ()); ("stop 2??" + ()); } catch (InterruptedException e) { (); } } }
Running results:
stop 1??false stop 2??false
Although the following code is called on the thread object in the class: (), then used
("stop 1??" + ()); ("stop 2??" + ());
To determine whether the thread represented by the thread object is stopped, but judging from the results printed by the console, the thread has not stopped, which also proves the explanation of the interrupted() method, testing whether the current thread has been interrupted. This current thread is main, it has never interrupted, so the print result is two false.
How to make the main thread interrupt effect?
public class Run2 { public static void main(String args[]){ ().interrupt(); ("stop 1??" + ()); ("stop 2??" + ()); ("End"); } }
The operation effect is:
stop 1??true stop 2??false End
The method interrupted() does determine whether the current thread is in a stopped state. 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 interrupt state 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 take a look at the inInterrupted() method below.
public class Run3 { public static void main(String args[]){ Thread thread = new MyThread(); (); (); ("stop 1??" + ()); ("stop 2??" + ()); } }
Running results:
stop 1??true stop 2??true
isInterrupted() and is cleared, so two true are printed.
3. Threads that can be stopped – exception method
With the knowledge points I learned before, you can use the for statement in the thread to determine whether the thread is in a stop state. If it is in a stop state, the subsequent code will no longer run:
public class MyThread extends Thread { public void run(){ (); for(int i=0; i<500000; i++){ if(()) { ("The thread has been terminated, the for loop is no longer executed"); break; } ("i="+(i+1)); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); (); try { (2000); (); } catch (InterruptedException e) { (); } } }
Running results:
... i=202053 i=202054 i=202055 i=202056 The thread has been terminated, forThe loop is no longer executed
Although the above example stops the thread, if there are still statements below the for statement, it will continue to run. See the following example:
public class MyThread extends Thread { public void run(){ (); for(int i=0; i<500000; i++){ if(()) { ("The thread has been terminated, the for loop is no longer executed"); break; } ("i="+(i+1)); } ("This is a statement outside the for loop and will be executed."); } }
The result of the use execution is:
... i=180136 i=180137 i=180138 i=180139 The thread has been terminated, forThe loop is no longer executed This isforLoop outside the statement,Will be executed
How to solve the problem of continuing to run the statement? Take a look at the updated code:
public class MyThread extends Thread { public void run(){ (); try { for(int i=0; i<500000; i++){ if(()) { ("The thread has been terminated, the for loop is no longer executed"); throw new InterruptedException(); } ("i="+(i+1)); } ("This is a statement outside the for loop and will be executed."); } catch (InterruptedException e) { ("Enter the catch in the class...."); (); } } }
The result of the use run is as follows:
... i=203798 i=203799 i=203800 The thread has been terminated, forThe loop is no longer executed Enter the classcatchIt's。。。 at (:13)
4. Stop in sleep
What effect will it be if the thread stops the thread in sleep() state?
public class MyThread extends Thread { public void run(){ (); try { ("The thread starts...."); (200000); ("Thread ends."); } catch (InterruptedException e) { ("Stopped in sleep, Entercatch, CallisInterrupted()The result of the method is:" + ()); (); } } }
The result of using run is:
Thread start。。。 Stopped in sleep, Entercatch, CallisInterrupted()The result of the method is:false : sleep interrupted at (Native Method) at (:12)
Judging from the printed results, if a thread is stopped in the sleep state, the catch statement will be entered and the stop state value will be cleared to make it false.
The previous experiment was to sleep first and then stop with interrupt(). In contrast, you should also pay attention to the learning process:
public class MyThread extends Thread { public void run(){ (); try { ("The thread starts...."); for(int i=0; i<10000; i++){ ("i=" + i); } (200000); ("Thread ends."); } catch (InterruptedException e) { ("Stop first, then encounter sleep, enter catch exception"); (); } } } public class Run { public static void main(String args[]){ Thread thread = new MyThread(); (); (); } }
Running results:
i=9998 i=9999 Stop first,Meet againsleep,Entercatchabnormal : sleep interrupted at (Native Method) at (:15)
5. Threads that can be stopped - brute force stop
Stop the thread using the stop() method is very violent.
public class MyThread extends Thread { private int i = 0; public void run(){ (); try { while (true){ ("i=" + i); i++; (200); } } catch (InterruptedException e) { (); } } } public class Run { public static void main(String args[]) throws InterruptedException { Thread thread = new MyThread(); (); (2000); (); } }
Running results:
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 exception
An exception is thrown when calling the stop() method, but usually, this exception does not need to be captured displayably.
public class MyThread extends Thread { private int i = 0; public void run(){ (); try { (); } catch (ThreadDeath e) { ("Enter exception catch"); (); } } } public class Run { public static void main(String args[]) throws InterruptedException { Thread thread = new MyThread(); (); } }
The stop() method is invalid, because if you force the thread to stop, it may cause some clean-up work to not be completed. Another situation is that the locked object is unlocked, resulting in the data not being processed synchronously and the data is inconsistent.
7. Undesirable consequences of releasing locks
Using stop() to release the lock will cause inconsistent results in data. If such a situation occurs, the data processed by the program may be damaged, which will eventually lead to errors in the program execution process. Be sure to pay special attention to:
public class SynchronizedObject { private String name = "a"; private String password = "aa"; public synchronized void printString(String name, String password){ try { = name; (100000); = password; } catch (InterruptedException e) { (); } } public String getName() { return name; } public void setName(String name) { = name; } public String getPassword() { return password; } public void setPassword(String password) { = password; } } public class MyThread extends Thread { private SynchronizedObject synchronizedObject; public MyThread(SynchronizedObject synchronizedObject){ = synchronizedObject; } public void run(){ ("b", "bb"); } } public class Run { public static void main(String args[]) throws InterruptedException { SynchronizedObject synchronizedObject = new SynchronizedObject(); Thread thread = new MyThread(synchronizedObject); (); (500); (); (() + " " + ()); } }
Output result:
b aa
Since the stop() method and the method marked as "expired/deactivated" in the JDK, it is obviously functionally flawed, so it is not recommended to use the stop() method in the program.
8. Stop threads using return
Using the method interrupt() in combination with return can also achieve the effect of stopping threads:
public class MyThread extends Thread { public void run(){ while (true){ if(()){ ("The thread was stopped!"); return; } ("Time: " + ()); } } } public class Run { public static void main(String args[]) throws InterruptedException { Thread thread = new MyThread(); (); (2000); (); } }
Output result:
... Time: 1467072288503 Time: 1467072288503 Time: 1467072288503 The thread was stopped!
However, it is still recommended to use the "exception throw" method to achieve thread stopping, because the exception can also be thrown up in the catch block, so that the thread stop event can be propagated.
This is the end of this article about three methods of Java terminating running threads. For more related content on Java terminating running threads, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!