Brief introduction
In Java multithreaded programming, the Java.lang.Thread type contains some of the column's method start (), Stop (), Stop (Throwable) and suspend (), Destroy () and resume (). With these methods, we can easily manipulate threads, but only the start () method is preserved in these methods.
In a Sun company article "Why are Thread.stop, thread.suspend and Thread.Resume deprecated?" Explains the reasons for abandoning these methods in detail. So how exactly should we stop the thread?
Suggested methods of use
In the Why are Thread.stop, thread.suspend and Thread.Resume deprecated? , we recommend that you stop the thread by using the following methods:
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
For a reason to use the volatile keyword, see http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930.
When a thread is in a non-running (run) state
When a thread is in the following state, it is not running:
* When the sleep method is invoked.
* When the wait method is invoked.
* When blocked by I/O, may be a file or network, and so on.
When the thread is in the above state, using the method described earlier is not available. At this time, we can use interrupt () to break the blocking situation, such as:
public void stop() {
Thread tmpBlinker = blinker;
blinker = null;
if (tmpBlinker != null) {
tmpBlinker.interrupt();
}
}