安全的終止線程
如果想終止線程最好不要使用 stop
方法审洞,因為 stop
方法在終結(jié)一個線程時不會保證線程的資源正常釋放帅刀,通常是沒有給予線程完成資源釋放工作的機會端圈,因此會導(dǎo)致程序可能工作在不確定狀態(tài)下蜓斧。
終止線程最好使用線程中斷標(biāo)識 isInterrupt
或者自定義一個 boolean
變量來控制是否需要停止任務(wù)并終止該線程盲镶。
Shutdown.java
import java.util.concurrent.TimeUnit;
/**
* 使用標(biāo)識安全的終止線程
*/
public class Shutdown {
public static void main(String[] args) throws InterruptedException {
Runner one = new Runner();
Thread countThread = new Thread(one, "CountThread");
countThread.start();
TimeUnit.SECONDS.sleep(1);
countThread.interrupt();
Runner two = new Runner();
countThread = new Thread(two, "CountThread");
countThread.start();
TimeUnit.SECONDS.sleep(1);
two.cancel();
}
private static class Runner implements Runnable {
private long i;
private volatile boolean on = true;
/**
* 通過線程中斷標(biāo)志位或則一個 boolean 變量來取消或者停止任務(wù)
*/
@Override
public void run() {
while (on && !Thread.currentThread().isInterrupted()) {
i++;
}
// 清理資源
System.out.println("Count = " + i);
}
public void cancel() {
on = false;
}
}
}