線程終止
通過(guò) stop 終止
已被 jdk 棄用,它可能導(dǎo)致線程安全問(wèn)題裹赴。
通過(guò) interrupt 終止
推薦使用的方式喜庞。
通過(guò)標(biāo)志位終止
代碼邏輯中增加一個(gè)判斷,用于控制程序終止棋返。用于代碼邏輯是一種循環(huán)執(zhí)行的業(yè)務(wù)邏輯
代碼演示
StopThread 實(shí)現(xiàn) i 自增 j 自增
public class StopThread extends Thread{
private int i=0,j=0;
@Override
public void run() {
++i;
try{
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
public void print() {
System.out.println("i=" + i + " j=" + j);
}
}
線程終止操作
public class Hello {
public static void main(String[] args) throws InterruptedException{
StopThread thread = new StopThread();
thread.start();
Thread.sleep(100);
//thread.stop(); 不推薦
thread.interrupt();
while (thread.isAlive()) {
// 確保線程已經(jīng)終止
System.out.println(thread.getState().toString());
} // 輸出結(jié)果
thread.print();
System.out.println(thread.getState().toString());
}
}
stop 終止輸出
TIMED_WAITING
i=1 j=0
TERMINATED
interrupt 終止輸出
TIMED_WAITING
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
RUNNABLE
i=1 j=1
TERMINATED
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at hello.StopThread.run(StopThread.java:10)
通過(guò)標(biāo)志位終止
public class Hello {
public volatile static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
while (flag) { // 判斷是否運(yùn)行
System.out.println("運(yùn)行中");
Thread.sleep(1000L);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
// 3秒之后延都,將狀態(tài)標(biāo)志改為False,代表不繼續(xù)運(yùn)行
Thread.sleep(3000L);
flag = false;
System.out.println("程序運(yùn)行結(jié)束");
}
}