The thread-stopping method in the thread class has a stop (), and the method of pausing and continuing the thread has suspend () and resume (). However, these methods have been abandoned.
Exception method Stop thread
On the code:
Public classTest { Public Static voidMain (string[] args) {MyThread thread=NewMyThread (); Thread.Start (); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } thread.interrupt (); }}classMyThreadextendsThread {@Override Public voidrun () {BooleanFlag =true; while(flag) {if( This. isinterrupted ()) {System.out.println ("Thread is about to stop"); Try { Throw Newinterruptedexception (); } Catch(interruptedexception e) {flag=false; }}} System.out.println ("The loop has jumped out and the thread stops"); }}
Print output:
The thread is about to stop and the thread stops.
When the Run method finishes executing, the thread will naturally end.
To stop a thread using return
Public classTest2 { Public Static voidMain (string[] args) {MyThread2 thread=NewMyThread2 (); Thread.Start (); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } thread.interrupt (); }}classMyThread2extendsThread {@Override Public voidrun () { while(true) { if( This. isinterrupted ()) {System.out.println ("Thread Stop"); return; } } }}
Print output:
Thread stop
Thread paused and resumed
Thread paused, resumed, and stopped, on the code:
Public classTest { Public Static voidMain (string[] args) {MyThread thread=NewMyThread (); Thread.Start (); Try{Thread.Sleep (1); Thread.mysuspend (); Thread.Sleep (1); Thread.myresume (); Thread.Sleep (1); Thread.mystop (); } Catch(Exception e) {e.printstacktrace (); } }}classMyThreadextendsThread {Private intCounts = 0; Private intStatus = 1; Private Final intSUSPEND =-1; Private Final intRUNNING = 1; @Override Public voidrun () {BooleanFlag =true; while(flag) {if( This. isinterrupted ()) {System.out.println (++counts + "-thread is about to stop"); Try { Throw Newinterruptedexception (); } Catch(interruptedexception e) {flag=false; } } Else if(Status = =SUSPEND) {System.out.println (++counts + "-Thread paused"); } Else if(Status = =RUNNING) {System.out.println (++counts + "-thread is still continuing"); }} System.out.println (++counts + "-already jumping out of the loop, thread stopped"); } Public voidMysuspend () {Status=SUSPEND; } synchronized Public voidMyresume () {Status=RUNNING; This. Notifyall (); } Public voidMystop () { This. Interrupt (); }}
Print output:
1-Thread is still continuing 2-thread paused 3-thread paused ... 42-Thread paused 43-thread paused 44-thread is still continuing 45-thread is still continuing 46-thread is still continuing ... 87-The thread is still continuing 88-the thread is still continuing 89-the thread is still continuing 90-the thread is still continuing 91-the thread is about to stop 92-it has jumped out of the loop and the thread has stopped
Java threads Stop, pause, and continue