The Stop method for multithreading stops is obsolete, so there is only one way to stop a thread, and the Run method ends. Because multithreading
The code that runs is usually a looping structure, so long as you control the loop, the Run method ends, that is, the thread ends. (Use tag to control loops)
Ps:
Special cases:
When the thread is in a frozen state, the tag is not read, and the thread does not end.
When there is no method specified to let the frozen thread resume running, the frozen state needs to be purged.
The thread class provides a method that is specifically designed to clear the frozen state of a thread--interrupt
Example of stopping a thread:
classStopthreaddemo { Public Static voidMain (string[] args) {//Create and open two threadsStopthread st =NewStopthread (); Thread T1=NewThread (ST); Thread T2=NewThread (ST); T1.start (); T2.start (); //Create a counter intnum = 0; //loop output in main thread//if the main thread outputs 60 sentences then stop the output and change the two threads that the mark stops opening. while(true) { if(num++ = = 60) {St.changeflag (); Break; } System.out.println (Thread.CurrentThread (). GetName ()+"............."+num); } }}classStopthreadImplementsrunnable{Private BooleanFlag =true; Public voidrun () { while(flag) {System.out.println (Thread.CurrentThread (). GetName ()+ "... run ..."); } }//ways to modify tags Public voidChangeflag () {flag=false; }}
stopping a thread by token
Special case Stop Thread example:
classStopthreadImplementsrunnable{Private BooleanFlag =true; //When a thread runs because it is marked as true, it goes into a frozen state and discards the eligibility for execution. Public synchronized voidrun () {intnum = 0; while(flag) {Try { This. Wait (); } Catch(interruptedexception e) {//a interruptedexception (interrupt exception) is thrown if the thread is forced to wakeSystem.out.println (Thread.CurrentThread (). GetName () + ". Exception. "); //If a interruptedexception (interrupt exception) occurs, someone is forcing the thread to wake, and the purpose of the wake is to have the thread end This. Changeflag (); } System.out.println (Thread.CurrentThread (). GetName ()+"... Run a ... "+num++); } }//ways to modify tags Public voidChangeflag () {flag=false; }}classStopthreaddemo { Public Static voidMain (string[] args) {//Create and open two threadsStopthread st =NewStopthread (); Thread T1=NewThread (ST); Thread T2=NewThread (ST); T1.start (); T2.start (); //Create a counter intnum = 0; //main thread loop output//if the main thread outputs 60 sentences, the output is stopped, and the thread in hibernation is forced to wake up by the interrupt method. while(true) { if(num++ = = 60) {t1.interrupt (); T2.interrupt (); Break; } System.out.println (Thread.CurrentThread (). GetName ()+"............."+num); } }}
How to end a thread when a thread freezes
Multithreading (Stopping threads)