For this question, first look at the deprecated methods in the thread class method. Suspend (), resume (), Stop ()/stop (Throwable obj), destroy ()
First, the Stop (Throwable obj) and destroy () methods are not supported directly in the latest Java, and there is no need to see them. All we need to do is look at suspend (), resume (), stop () these three;
Suspend ()--to suspend execution of the current thread
Resume ()--let the current thread resume execution
When suspend () is called, the thread does not dispose of the object, so when multithreaded, if the other thread is going to use an object that is occupied by a suspend thread, it must wait until it is resume (), and the process is very prone to deadlock.
So, they is deprecated!
and stop () is the least, because you do not know its state on the Stop (), release all the locks can be released, and if the Run method exists in sync, it does not necessarily stop~ positive and negative direction, this method is not suitable.
Note: For the abandoned method itself to understand can, more or to analyze the cause of abandonment, if you like to step up the words ~
About stopping a running thread, the official recommendation is to set the variable to close. The shape is the same as:
Public classAPP { Public Static voidMain (string[] args)throwsException {classMyThreadextendsThread {BooleanFlag =true; @Override Public voidrun () { while(flag) {//Do something Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("I ' m running!"); } System.out.println ("I ' m dead!"); } Public voidStopthread () {flag=false; }} MyThread Thread=NewMyThread (); Thread.Start (); Thread.Sleep (3000); Thread.stopthread (); }}
That is, by setting a variable to close the thread, of course, if you are doing it once, then of course there is no need to set the variable, because this thread does not need to handle the stop behavior alone.
Second, this is said to be a variable but there are many clever places for this variable setting, such as the following type:
Public classAPP { Public Static voidMain (string[] args)throwsException {classMyThreadextendsThread {BooleanIsRunning =true; @Override Public voidrun () { while(isrunning) {//Do something Try{Thread.Sleep (1000); } Catch(interruptedexception e) {System.out.println (E.getmessage ()); IsRunning=false; } System.out.println ("I ' m running!"); } System.out.println ("I ' m dead!"); }} MyThread Thread=NewMyThread (); Thread.Start (); Thread.Sleep (3000); Thread.Interrupt (); }}
This is basically the way to operate ~
Java re-learning-stop a running thread