1. 使用標誌位
public class ThreadEx implements Runnable {
private volatile boolean isStoped = false;
public void run() {
while (isStoped) {
// do something
}
}
public void stop {
isStoped = true;
}
}
上面這種方法當啓動線程後在關閉時需要手動調用stop方法關閉線程,如果程序中只有一個線程後臺運行,那麼可以採用以下方式保證程序重新啓動時,正確關閉上一次打開的後臺線程,避免內存溢出。
public class Handler {
private static ThreadEx t;
public static void start() {
if (t != null)
t.stop();
t = new ThreadEx();
new Thread(t).satrt();
}
}
2. 使用中斷
public class InterruptedExample {
public static void main(String[] args) throws Exception {
InterruptedExample interruptedExample = new InterruptedExample();
interruptedExample.start();
}
public void start() {
MyThread myThread = new MyThread();
myThread.start();
try {
Thread.sleep(3000);
myThread.cancel();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class ThreadEx extends Thread{
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("interrupt");
// 注意異常處理
Thread.currentThread().interrupt();
}
}
System.out.println("stop");
}
public void stop(){
interrupt();
}
}
}
對線程調用interrupt()方法,不會真正中斷正在運行的線程,只是發出一個請求,由線程在合適時候結束自己。正常情況下,線程接收到interrupt會在下一次判斷中跳出循環,但是如果線程處於掛起狀態,此時收到interrupt請求就會拋出異常,拋出InterruptedException後,中斷標記會被重新設置爲false,所以在InterruptedExample例子裏,在接收到中斷請求時,標準做法是執行Thread.currentThread().interrupt()恢復中斷,讓線程退出。
參考
http://www.jianshu.com/p/536b0df1fd55
http://blog.csdn.net/xplee0576/article/details/45133791