簡介
在Java的多線程編程中,java.lang.Thread類型包含了一些列的方法start(), stop(), stop(Throwable) and suspend(), destroy() and resume()。通過這些方法,我們可以對線 程進行方便的操作,但是這些方法中,只有start()方法得到了保留。
在Sun公司的一篇文章《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? 》中詳細講解了捨棄這些方法的原因。那麼,我們究竟應該如何停止線程呢?
建議使用的方法
在《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? 》中,建 議使用如下的方法來停止線程:
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();
}
}
關於使用volatile關鍵字的原因,請查看 http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930。
當線程處於非運行(Run)狀態
當線程處於下面的狀況時,屬於非運行狀態:
* 當sleep方法被調用。
*當wait方法被調用。
*當被I/O阻塞,可能是檔案或者網路等等。
當線程處於上述的狀態時,使用前面介紹的方法就不可用了。這個時候,我們可以使用 interrupt()來打破阻塞的情況,如:
public void stop() {
Thread tmpBlinker = blinker;
blinker = null;
if (tmpBlinker != null) {
tmpBlinker.interrupt();
}
}