Java并沒有提供真正中斷線程的方法妈拌,<font color=red>中斷線程最好的方法就是讓線程執(zhí)行完成自然終止</font>,stop(),suspend(),resume()等方法會(huì)導(dǎo)致不安全或者死鎖等問題,均已經(jīng)廢棄。
有兩種方法中斷線程肮疗,一種為通過自定義變量設(shè)置退出標(biāo)志,一種通過interrupt方法扒接,本質(zhì)沒有區(qū)別伪货。<font color=red>但是第二種方式可以處理阻塞中的線程,推薦使用钾怔。</font>
第一種:通過自定義變量設(shè)置退出標(biāo)志碱呼,讓線程自然終止
public class ThreadFlag extends Thread {
public boolean exit = false;
public void run() {
while (!exit) {
System.out.println("我是子線程,我在執(zhí)行");
}
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(5000); // 主線程延遲5秒宗侦,看效果
thread.exit = true; // 終止線程thread
thread.join();
System.out.println("線程退出!");
}
}
這種開關(guān)的方式使用大部分情況愚臀,但是當(dāng)遇到線程阻塞時(shí),就沒有辦法了會(huì)一直卡在那矾利,如下面的示例代碼姑裂。
public class ThreadFlag extends Thread {
public boolean exit = false;
public void run() {
while (!exit) {
try {
sleep(1000_000);//
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我是子線程馋袜,我在執(zhí)行");
}
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(5000); // 主線程延遲5秒,看效果
thread.exit = true; // 終止線程thread
thread.join();
System.out.println("線程退出!");
}
}
第二種:使用線程的interrupt方法
這種方法不會(huì)真正停止線程炭分,需要自己根據(jù)interrupted標(biāo)志自行處理讓線程自然結(jié)束,相比于第一種方式有一個(gè)好處就是可以處理阻塞中的線程剑肯,它可以迅速中斷被阻塞的線程捧毛,拋出一個(gè)InterruptedException,把線程從阻塞狀態(tài)中釋放出來让网,第一種則不行呀忧。
public class ThreadInterrupt extends Thread {
public void run() {
while (!isInterrupted()) {//判斷結(jié)束標(biāo)志
try {
sleep(1000_000);//
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("我是子線程,我在執(zhí)行");
}
}
public static void main(String[] args) throws Exception {
ThreadInterrupt thread = new ThreadInterrupt();
thread.start();
sleep(5000); // 主線程延遲5秒溃睹,看效果
thread.interrupt();
thread.join();
System.out.println("線程退出!");
}
}