As previously described, the shutdown thread can use INTERRUPTE, which can be tagged to let run execution end. Now let's look at a few ways.
Method 1, use the Interrupte method to execute, by throwing interruptedexception to end the run.
Package Secondthreadstudy;import Java.lang.interruptedexception;public Class MyThread extends Thread {@Overridepublic void Run () {super.run (); try{for (int i = 0; i< 500000; i++) {//determines if the object thread interrupts if (this.interrupted ()) {System.out.println (" Has interrupted! I am quit! "); throw new Interruptedexception ();} System.out.println ("I am not executed, yeah!");} System.out.println ("I am not executed, too, yeah!");} catch (Interruptedexception e) {System.out.println ("Exception has been catched"); E.printstacktrace ();}}}
Test
Package Thirdthread;public class Test {public static void main (string[] args) {Try{mythread boy = new MyThread (); Boy.start ( ); Thread.Sleep (+); Boy.interrupt ();} catch (Interruptedexception e) {System.out.println ("main catch"); E.printstacktrace ();}}}
Method 2, use sleep and interrupt () to stop the thread.
Package Thirdthread;import Java.lang.interruptedexception;public Class MyThread extends Thread {@Overridepublic void Run () {super.run (); Try{system.out.println ("Mythread sleep"); Thread.Sleep (10000); System.out.println ("has interrupted! I am quit! ");} catch (Interruptedexception e) {System.out.println ("Exception has been catched"); E.printstacktrace ();}}}
Method 3, use stop, not recommended, there is nothing to say, that is, stop, no matter where the thread executes, as long as stop will stop, release the lock, for synchronous multithreading is very dangerous. Not to cite examples.
Method 4, using return, is actually in the Run method, using isinterrupted () to judge, and then return directly, let the Run method end. There's nothing to explain.
Method 5, in fact, using the Interrupte method, my understanding is essentially using a Boolean, assuming that the Interrupte method is not interrupted, but the thread class set a flag field such as flag, function equivalent to Interrupte, just more controllable, in the Run method , sets the loop, and executes the rest of the code in the Run method, even if the flag is checked for true,true and then return directly. By setting the flag of the thread to make the thread aware of the appropriate rollout, and each exit will be completed after the relevant work. Not happy to write the code.
This article is from the "Happy Cup of Tea" blog, please be sure to keep this source http://gugw9handsome.blog.51cto.com/1187812/1784200
Ways to stop Java threads