Java stops the thread
Stop () is out of date.
Stop the thread: the run () method ends.
Turn on multi-threaded running, usually the code is a loop structure.
As long as you control the loop, you can let run () end, which ends the thread.
Class StopThread implements Runnable {private boolean flag = true; @ Override public void run () {while (flag) {System.out.println (Thread.currentThread (). GetName () + ".run");} public void changeFlag () {flag = false;}} public class StopThreadDemo {public static void main (String [] args) {StopThread st = new StopThread () Thread T1 = new Thread (st); Thread T2 = new Thread (st); t1.start (); t2.start (); int num = 0; while (true) {if (num++ = = 60) {st.changeFlag (); break } System.out.println (Thread.currentThread (). GetName () + "." + num);}
Special case: when the thread is frozen, the tag will not be read, so the thread will not end.
When there is no specified way to restore the frozen thread to the running state, it is necessary to clear the freeze and force the thread to return to the running state, so that the flag can be operated to let the thread end.
This method is provided in the Thread class: interrupt ()
Class StopThread implements Runnable {private boolean flag = true; @ Override public synchronized void run () {while (flag) {try {wait ();} catch (InterruptedException e) {System.out.println (Thread.currentThread (). GetName () + ".exception"); flag = false } System.out.println (Thread.currentThread (). GetName () + ".. run");} public void changeFlag () {flag = false;}} public class StopThreadDemo {public static void main (String [] args) {StopThread st = new StopThread (); Thread T1 = new Thread (st); Thread T2 = new Thread (st); t1.start () T2.start (); int num = 0; while (true) {if (num++ = = 60) {/ / st.changeFlag (); t1.interrupt (); t2.interrupt (); break } System.out.println (Thread.currentThread (). GetName () + "." + num);} System.out.println ("over");}}