Thread termination method
 
1. Use the 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 () determines that the Thread can be terminated and plays a flag role.
 
 
 
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 this method has been discarded. Although yes, it is not recommended. For frozen threads, the flag alone is not enough to terminate the thread. When the main thread ends, t2 t1 directly wait (). If the thread is frozen, it cannot read the mark, therefore, the second thread termination method interrupt () is introduced. It is invalid to terminate the thread directly using the interrupt () method, but interrupt () method can be used to forcibly restore a thread from the frozen state to the running state, so that the thread can return to the State that has the CPU execution qualification, but there will be an interrupt exception (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 that if this parameter is not added, the thread continues to wait and the main thread ends T2.} 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 = 20) // when I reaches 20, end all threads {// s. changeFlag (); t1.interrupt (); t2.interrupt (); break;} System. out. println ("Main. main "+ I);} System. out. println ("Final ");}}