How to stop a thread correctly
This article (How to stop thread) gives a good answer to the proper stopping of threads, summed up 3 points below (when stopping threads):
1. Use the violate Boolean variable to identify whether the thread is stopped
2. When stopping a thread, you need to invoke the interrupt () method of the stop thread, because the thread may be waiting () or sleep () to increase the immediacy of the stop thread
3. For blocking IO processing, try to use Interruptiblechannel instead of blocking IO
The core is as follows:
If you are are writing your own small thread then you should follow the following code.
private volatile Thread mythread;
public void Stopmythread () {Thread tmpthread = mythread;
Mythread = null;
if (tmpthread!= null) {tmpthread.interrupt ();
} public void Run () {if (Mythread = null) {return;//stopped before started.
try {//All "run () method" code goes here ...//do some work Thread.yield ();
Let another thread have some time perhaps to stop this one. if (Thread.CurrentThread (). isinterrupted ()) {throw new Interruptedexception ("Stopped by Ifinterruptedstop" (
)"); }//Do some more work ...} catch (Throwable t) {//Log/handle all Errors here}}