不正確的線程中止--Stop
Stop: 中止線程,并且清除監(jiān)控鎖的信息,但是可能導(dǎo)致線程安全問題,JDK不建議使用。
Destroy: JDK未實(shí)現(xiàn)該方法。
public class Demo3 {
public static void main(String[] args) {
StopThread thread = new StopThread();
thread.start();
thread.stop();
while (thread.isAlive()){
}
thread.print();
}
}
class StopThread extends Thread{
private int i = 0,j = 0;
public void run(){
++i;
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
public void print(){
System.out.println("i = " + i +", j =" + j);
}
}
理想輸出:i = 0 , j =0
程序執(zhí)行結(jié)果: i = 1, j =0
得出結(jié)論: 沒有保證同步代碼塊里面數(shù)據(jù)的一致性,破壞了線程安全。
正確的線程中止--interrupt
如果目標(biāo)線程在調(diào)用Object class的wait()、wait(long)或wait(long,int)方法、join()、join(long, int) 或sleep(long,int)方法時(shí)被阻塞,那么interrupt會(huì)生效,該線程的中斷狀態(tài)將被清除,拋出InterruptedException異常。
如果目標(biāo)線程是被I/O或者NIO中的Channel所阻塞,同樣,I/O操作會(huì)被中斷或者返回特殊異常值。達(dá)到中止線程的目的。
如果以上條件都不滿足,則會(huì)設(shè)置此線程的中斷狀態(tài)。
對(duì)面上述的示例,將stop改為interrupt后,最終輸出為“i =1, j =1",數(shù)據(jù)一致。
正確的線程中止--標(biāo)志位
代碼邏輯中,添加一個(gè)判斷,用來控制線程執(zhí)行的中止。
public class Demo4 {
public volatile static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
try {
while (flag){
System.out.println("線程正在運(yùn)行");
Thread.sleep(1000L);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(3000L);
flag = false;
System.out.println("程序運(yùn)行結(jié)束");
}
程序運(yùn)行結(jié)果:
線程正在運(yùn)行
線程正在運(yùn)行
線程正在運(yùn)行
程序運(yùn)行結(jié)束