Description:
The thread may need to stop on condition judgment while running, from the API to force terminate the thread with the Stop method, but this method is not recommended by the official, this is a method that expires, because if the thread is forced to stop, it is possible that some cleanup work will not be completed. Locked objects are also "unlocked", which may result in data being not synchronized, resulting in data problems.
In Java, there are many ways to terminate, such as:
1, the use of exit flags, so that the normal exit of the thread, that is, set a variable, when the variables are satisfied when the completion, that is, the equivalent of the Run method after the completion of the thread termination;
2, the use of interrupt method in the disconnection process;
The main record under the interrupt method to stop the thread, the code is very simple, the specific code is as follows:
[HTML] View plain copy print? public class stoptest extends thread { public static void main (String[] args) { try { //Open Thread stoptest thread = new stoptest (); thread.start (); thread.sleep (; ) //set thread stop state Thread.Interrupt (); &nbsP; system.out.println ("Stopped," +thread.isinterrupted ()); } catch (exception e) { e.printstacktrace (); } } @Override public void run () { // TODO Auto-generated method stub for (int i = 0; i < 100000; i++) { system.out.println ( "I=" + i); // Stop thread business According to thread state if (this.isinterrupted ()) { system.out.println ("Current thread:" + this.getname () + "stopped." "); break; } } SYSTEM.OUT.PRINTLN ("End!!!"); } }
Run the output:
i=15313
i=15314
i=15315
Whether it stopped, true
Current thread: Thread-0 stopped.
End!!!
The above code stops the thread by judging the thread state interrupted () method, much better than stopping it directly with stop!