前言
上篇文章講解了多線程的兩種創建方法,那麼本文就帶來多線程的停止方法。
一、線程的停止
1.stop方法
stop是jdk不推薦使用的一個方法,stop是強行停止一個線程,可能使一些清理性的工作得不到完成。還可能對鎖定的內容進行解鎖,容易造成數據不同步的問題,所以不推薦使用。
/**
* @version 1.0
* @Description 線程stop停止方式demo
* @Author wb.yang
*/
public class ThreadStopDemo {
public static class TestThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("this is :" + i);
}
}
}
public static void main(String[] args) throws InterruptedException {
TestThread testThread = new TestThread();
testThread.start();
Thread.sleep(1);
testThread.stop();
}
}
如上面代碼所示,啓動了一個線程,循環了一萬次輸出,在啓動後又調用了stop方法,停止了線程。
這個是代碼運行的結果,從中可以看出,僅僅輸出到44線程便停止了,在實際的應用中,很容易出現線程安全問題,所以不推薦使用。
2.interrupt方法
使用interrupt方法進行中斷線程。interrupt是一個標識位,通過這個標識判斷線程的狀態,決定是否中斷線程。通過代碼來看一下把
/**
* @version 1.0
* @Description interrupt標識位demo
* @Author wb.yang
*/
public class InterruptDemo {
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS");
public static class TestThread extends Thread {
@Override
public void run() {
//判斷中斷標識位
while (!isInterrupted()) {
try {
//輸出信息
System.out.println("UseThread:" + format.format(new Date()));
Thread.sleep(3000);
} catch (InterruptedException e) {
//檢測到中斷異常
System.out.println("UseThread catch interrput flag is "
+ isInterrupted() + " at "
+ (format.format(new Date())));
interrupt();
e.printStackTrace();
}
}
//線程終止結尾輸出
System.out.println(" UseThread interrput flag is "
+ isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
TestThread testThread = new TestThread();
testThread.start();
//打印主線程時間
System.out.println("Main:" + format.format(new Date()));
Thread.sleep(800);
// 開始終止線程
System.out.println("Main begin interrupt thread:" + format.format(new Date()));
testThread.interrupt();
}
}
上面是使用interrupt方法進行終止線程,他給了線程的標識爲true,然後在isInterrupted方法中判斷標識狀態,如果是true,終止狀態,這終止線程。並且有一個InterruptedException異常,這個異常也是對標識位操作的處理。
這是輸出結果,明顯看出線程是執行完結束的。這個就較爲線程安全,不像stop一樣強行停止線程。
Thread.java提供了三個方法,interrupt主動進行停止線程,isInterrupted判斷線程狀態,不會清楚線程狀態。interrupted方法會在檢測的同時,如果發現標誌爲true,則會返回true,然後把標誌置爲false.
總結
線程停止還是不推薦使用stop,推薦使用interrupt方法,按照業務需求合理使用isInterrupted和interrupted方法來處理線程狀態。