Java multi-thread stop thread

Source: Internet
Author: User
Tags thread stop

Stopping threads in multithreaded development is an important technical point. Stopping a thread in the Java language is not as straightforward as a break statement, and requires some tricky processing.

first, the anomaly method

Using the exception method to stop a thread, we first need to look at the usage of the two methods:

1. Interrupt () method
public class MyThread extends thread{@Overridepublic void Run () {for (int i = 1; I <= 10000; i++) {System.out.println (" I= "+i);}} public static void Main (string[] args) throws Exception {MyThread thread=new MyThread (); Thread.Start (); Thread.Sleep (10) ; Thread.Interrupt ();}}

The above example calls the interrupt () method to stop the thread, but the interrupt () method does not use the same effect as the For+break statement to stop the loop immediately. The call to the interrupt () method is simply a stop mark on the current thread and does not really stop. So what if we stop the thread? We then looked down.
2. Determine if the thread is a stopped state
1), Interrupted ()
public class MyThread extends thread{@Overridepublic void Run () {for (int i = 1; I <= 10000; i++) {System.out.println (" I= "+i);}} public static void Main (string[] args) throws Exception {Try{mythread thread=new MyThread (); Thread.Start (); thread.sleep (+); Thread.Interrupt (); System.out.println ("Did the thread stop 1?") ---> "+thread.interrupted ()); System.out.println ("Did the thread stop 2?") ---> "+thread.interrupted ());} catch (Exception e) {e.printstacktrace ();} System.out.println ("End");}}

The result of printing from the console is that the thread does not stop, which means that the interrupted () test is not interrupted because the current thread is main, it is not interrupted, so the result of printing is two false.how to cause the main thread to have an interrupt effect. We are looking at the following example:
public class Mythread{public static void Main (string[] args) {Thread.CurrentThread (). interrupt (); System.out.println ("Did the thread stop 1?") ----> "+thread.interrupted ()); System.out.println ("Did the thread stop 2?") ----> "+thread.interrupted ()); System.out.println ("End");}}


Judging from the above results, the interrupted () method does determine whether the current thread is a stopped state. But why the 2nd value is false. It turns out that the first time the method is called twice, the interrupt state is cleared, and the second call returns Flase.
2), isinterrupted ()
public class MyThread extends thread{@Overridepublic void Run () {for (int i = 1; I <= 10000; i++) {System.out.println (" I= "+i);}} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Sleep (10); Thread.Interrupt (); System.out.println ("Did the thread stop 1?") ---> "+thread.isinterrupted ()); System.out.println ("Did the thread stop 2?") ---> "+thread.isinterrupted ());} catch (Exception e) {e.printstacktrace ();} System.out.println ("End");}}


The result shows that the method isinterrupted () is not cleared, so two true is printed.
3. Stop Thread
public class MyThread extends thread{@Overridepublic void Run () {for (int i = 1; I <= 10000; i++) {if (this.interrupted ( ) {System.out.println ("Thread is stopped, I'm quitting."); break;} System.out.println ("i=" +i); System.out.println ("If this is still a loop, then I will continue to execute." Thread does not stop ");} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Sleep (10); Thread.Interrupt (); System.out.println ("End");} catch (Exception e) {e.printstacktrace ();}}}


If this is the case, the thread does not stop. Now we are modifying the code, the so-called exception method to stop the thread.
public class MyThread extends thread{@Overridepublic void Run () {try{for (int i = 1; I <= 10000; i++) {if (This.interrup Ted ()) {System.out.println ("Thread is stopped, I'm quitting."); throw new Interruptedexception ();} System.out.println ("i=" +i); System.out.println ("Have I been executed?" ");} catch (Interruptedexception e) {System.out.println ("---this thread has stopped---"); E.printstacktrace ();}} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Sleep (10); Thread.Interrupt (); System.out.println ("End");} catch (Exception e) {e.printstacktrace ();}}}



second, stop in the sleepWhat happens if a thread stops a thread in the sleep () state?
public class MyThread extends thread{@Overridepublic void Run () {try{system.out.println ("run Start"); Thread.Sleep (1000000); System.out.println ("Run End");} catch (Interruptedexception e) {System.out.println ("Sleep is stopped, state:--->" +this.isinterrupted ()); E.printstacktrace ( );}} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Interrupt (); Thread.Sleep (1000);} catch (Exception e) {System.out.println ("main catch"); E.printstacktrace ();}}}


from the results we can see that when the thread sleeps, it stops a thread, is abnormal, and clears the stop state. We are in front of the abnormal stop thread, are sleep first, in the stop thread, with the opposite of the operation, I need to note when writing code.
public class MyThread extends thread{@Overridepublic void Run () {try{for (int i = 1; I <= 10000; i++) {System.out.print ln ("i=" +i);} System.out.println ("Run Start"); Thread.Sleep (1000000); System.out.println ("Run End");} catch (Interruptedexception e) {System.out.println ("thread was stopped, in sleep, state:--->" +this.isinterrupted ()); E.printstacktrace ();}} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Interrupt ();} catch (Exception e) {System.out.println ("main catch"); E.printstacktrace ();}}}




iii. cessation of violence
public class MyThread extends thread{private int i=0; @Overridepublic void Run () {Try{while (true) {i++; System.out.println ("i=" +i); Thread.Sleep (1000);}} catch (Exception e) {e.printstacktrace ();}} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Sleep (6000); Thread.stop ();} catch (Exception e) {e.printstacktrace ();}}}


The Stop () method has been deprecated, if forcing the thread to stop, there can be some cleanup work is not completed, there is a lock on the object to understand the lock, resulting in data synchronization phenomenon, so the development time to prohibit the use of this method to violence to stop the thread.
Iv. using return to stop the thread
public class MyThread extends thread{private int i=0; @Overridepublic void Run () {Try{while (true) {i++;if (this.interrupte D ()) {System.out.println ("thread stopped"); return;} System.out.println ("i=" +i);} catch (Exception e) {e.printstacktrace ();}} public static void Main (string[] args) {try{mythread thread=new MyThread (); Thread.Start (); Thread.Sleep (+); Thread.Interrupt ();} catch (Exception e) {e.printstacktrace ();}}}




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

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java multi-thread stop thread

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.