??一般我們在使用線程的過程中會遇到中斷一個線程的請求,java中有stop劝枣、suspend等方法埃元,但被認為是不完全的,所以棄用了谚赎,現(xiàn)在在Java中可以通過iterrupt來請求中斷線程淫僻。
??在Java中主要通過三個方法來進行中斷線程操作:
??(1)interrupt()诱篷,進行線程中斷操作,將線程中的中斷標(biāo)志位置位雳灵,置為true棕所;
??(2)interrupted(),對線程中斷標(biāo)識符進行復(fù)位悯辙,重新置為false琳省;
??(3)isInterrupt(),檢查中斷標(biāo)識符的狀態(tài)躲撰,ture還是false针贬;
??先來看看interrupt()方法,
public class ThreadTest {
public static class MyTestRunnable implements Runnable{
@Override
public void run() {
while (Thread.currentThread().isInterrupted()){ //獲得當(dāng)前子線程的狀態(tài)
System.out.println("停止");
}
}
public static void main(String[] args) {
MyTestRunnable myTestRunnable=new MyTestRunnable();
Thread thread=new Thread(myTestRunnable, "Test");
thread.start();
thread.interrupt();
}
}
運行后的結(jié)果為:??發(fā)現(xiàn)他會循環(huán)打印結(jié)果拢蛋,線程仍在不斷運行桦他,說明它并不能中斷運行的線程,只能改變線程的中斷狀態(tài)瓤狐,調(diào)用interrupt()方法后只是向那個線程發(fā)送一個信號瞬铸,中斷狀態(tài)已經(jīng)設(shè)置,至于中斷線程的具體操作础锐,在代碼中進行設(shè)計嗓节。
要怎樣結(jié)束這樣的循環(huán),在循環(huán)中添加一個return即可:
public class ThreadTest {
public static class MyTestRunnable implements Runnable{
@Override
public void run() {
while (Thread.currentThread().isInterrupted()){ //獲得當(dāng)前子線程的狀態(tài)
System.out.println("停止");
return皆警;
}
}
現(xiàn)在是線程沒有堵塞的情況下拦宣,線程能夠不斷檢查中斷標(biāo)識符,但是如果在線程堵塞的情況下信姓,就無法持續(xù)檢測線程的中斷狀態(tài)鸵隧,如果在阻塞的情況下發(fā)現(xiàn)中斷標(biāo)識符的狀態(tài)為true,就會在阻塞方法調(diào)用處拋出一個InterruptException異常意推,并在拋出異常前將中斷標(biāo)識符進行復(fù)位豆瘫,即重新置為false;需要注意的是被中斷的線程不一定會終止,中斷線程是為了引起線程的注意,被中斷的線程可以決定如何去響應(yīng)中斷菊值。
??如果不知道拋出InterruptedException異常后如何處理塘安,一般在catch方法中使用Thread.currentThread().isInterrupt()方法將中斷標(biāo)識符重新置為true
@Override
public void run() {
try {
sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
下面來看看如何使用interrupt來中斷一個線程祖屏,首先先看如果不調(diào)用interrupt()方法:
public static class MyTestRunnable implements Runnable{
private int i;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()){
i++;
System.out.println("i = "+i);
//return;
}
System.out.println("停止");
}
}
public static void main(String[] args) {
MyTestRunnable myTestRunnable=new MyTestRunnable();
Thread thread=new Thread(myTestRunnable, "Test");
thread.start();
}
}
結(jié)果為:??可以看出在沒有調(diào)用interrupt方法將中斷標(biāo)識符置為ture的時候号坡,線程執(zhí)行的判斷是循環(huán)中的方法所以是循環(huán)打印造虏,下面再看添加了interrupt方法后的結(jié)果:
public static void main(String[] args) {
MyTestRunnable myTestRunnable=new MyTestRunnable();
Thread thread=new Thread(myTestRunnable, "Test");
thread.start();
thread.interrupt();
}
}
因為中斷標(biāo)識符被置為了true所以執(zhí)行的是下面的語句儿子,然后線程結(jié)束瓦哎。