Java終止正在運作的線程的方式有如下三種
- 1 使用退出标志,使線程正常退出,也就是run方法完成後線程終止
- 2 使用stop方法強行終止線程(已過時),但是不推薦使用這個方法
- 3 使用interrupt方法中斷線程
1 使用退出标志,使線程正常退出,也就是run方法完成後線程終止
當run方法正常執行完,線程也就停止了,當有循環時,可設定一個标志變量,為真時運作,否則退出循環,主要代碼如下:
public void run() {
while(flag){
//do something
}
}
想要終止運作時,隻需設定flag值為false即可。
2 使用stop方法強行終止線程(已過時)
使用stop()方法能立即停止線程,但是可能使一些請理性工作得不到完成。另一種情況就是對鎖鎖定的對象經行了“解鎖”,導緻資料得不到同步的處理,出現不一緻的問題
3 使用interrupt方法中斷線程
值得注意的是,interrupt()方法并不能真正停止線程,而是在目前線程打了一個停止的标記,可用以下方法停止線程。
public void run() {
while (true) {
if (this.interrupted())
break;
System.out.println("running");
}
System.out.println("退出線程");
}
調用interrupt()方法,this.interrupted()結果為true,退出循環,但會繼續執行System.out.println(“退出線程”);然後正常退出線程。可以采用抛異常的方式終止線程,代碼如下
public void run() {
try {
while (true) {
if (this.interrupted()) {
throw new InterruptedException();
}
System.out.println("running");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}