1. Use the identifier flag to stop.
public void Run () {//TODO auto-generated method Stubwhile (flag) {SYSTEM.OUT.PRINTLN (name + ":" + (++num)); if (num==10000) Changeflag ();//thread.currentthread (). interrupt ();}} public void Changeflag () {flag=false;}
Or:
public void Changeflag () {flag=false;} public void Run () {//TODO auto-generated method Stubwhile (flag) {SYSTEM.OUT.PRINTLN (name + ":" + (++num));}} public static void Main (string[] args) {Simplethreaddemo simpleThreadDemo1 = new Simplethreaddemo ("Sting"); thread T1 = new Thread (SIMPLETHREADDEMO1); T1.start (); int I=0;while (TRUE) {if (++i==100000) { Simplethreaddemo1.changeflag (); break;}}}
2. Use the interrupt () method to stop, but use (! Thread.interrupted ()) to determine if a thread can be terminated and flag is played
public void Run () {//TODO auto-generated method Stubwhile (! Thread.interrupted ()) {System.out.println (name + ":" + (++num)), if (num==10000) Thread.CurrentThread (). interrupt ();}}
Or:
public void Run () {//TODO auto-generated method Stubwhile (! Thread.interrupted ()) {System.out.println (name + ":" + (++num));}} public static void Main (string[] args) {Simplethreaddemo simpleThreadDemo1 = new Simplethreaddemo ("Sting"); thread T1 = new Thread (SIMPLETHREADDEMO1); T1.start (); int I=0;while (TRUE) {if (++i==100000) {t1.interrupt (); break;}}}
3. You can also use the Stop () method to terminate the thread, but the method has been deprecated, although it is possible, but it is deprecated. For a frozen thread that is not enough to terminate a thread by flag only, the main thread ends, T2 t1 directly wait (), if the thread is frozen, it cannot read the tag, so it introduces the second way to end the thread interrupt (), Terminating a thread directly with the interrupt () method is not valid, but the interrupt () method can handle the type of forced recovery of a thread from a frozen state to a running state, returning the thread to a state with CPU execution qualification. However, an interrupt exception will occur (Interruptexception)
Class Stopthread implements Runnable{private Boolean flag = true;public synchronized void run () {while (flag) {try {wait ();} catch (Interruptedexception e) {//Todo:handle exceptionSystem.out.println (Thread.CurrentThread (). GetName () + " ... "+e); flag = false;//Note processing, not adding this will cause the thread to continue to wait, the main thread ends T1 T2 not end}system.out.println (Thread.CurrentThread (). GetName () +"-++--");}} public void Changeflag () {flag = false;}} public class Main{public static void Main (string[] args) {stopthread s = new Stopthread (); thread T1 = new thread (s); Thread t2 = new Thread (s); T1.start (); T2.start (); int i = 0;while (true) {if (++i = =)//i reaches 20 to end all threads {//s.changeflag (); T1.interrupt (); T2.interrupt (); break;} System.out.println ("Main.main" +i); System.out.println ("Final");}}
Methods for terminating Threads