1, the first is also the most common one is the use of State bits
public class Task extends Thread {
Private volatile Boolean flag= true;
public void Stoptask () {
Flag = false;
}
@Override
public void Run () {
while (flag) {
/* Do your no-block task */
}
}
}
This is the most classic way to safely terminate the current thread, the structure is simple refining, recommended to use. But this is also flawed, and there is no way to terminate a thread when the execution of a while loop, such as IO, is timed out.
2. Terminating a thread by using the Stop method
Use the Stop method to forcibly terminate a running or suspended thread. We can use the following code to terminate the thread:
Thread.stop ();
Although using the above code can terminate a thread, using the Stop method is dangerous, just like suddenly shutting down the computer, rather than shutting down as a normal program, it is not recommended to use the Stop method to terminate the thread.
3. Terminating a thread using the interrupt method
Using the interrupt method to end a thread can be divided into two situations:
(1) The thread is in a blocked state, such as using the Sleep method.
(2) Use while (! Isinterrupted ()) {...} To determine if a thread has been interrupted.
In the first case, using the interrupt method, the sleep method throws a Interruptedexception exception, and in the second case the thread exits directly.
Logically stop one thread in Java