java中有3中方式可以終止正在運行的線程
1.使用退出標誌,正常退出,也就是當run方法完成後終止
2.使用stop方法強行停止,這是一個已經過期的方法,不推薦使用,可以使數據造成不一樣的後果
3.使用interrupt方法中斷線程
這裏主要講一下:interrupt的使用
interrupt()方法的效果並不像for+break語句那樣,馬上停止循環。當線程調用interrupt()方法時,該方法只是在當前線程中打了一個停止的標記,並不是馬上停止,
需要配合線程中的另外兩個方法來輔助,即:Thread.java 中的interrupted()方法和isInterrupt()方法
(1)this.interrupted():判斷當前線程是否已經中斷,返回類型boolean,並且有清除中斷狀態的功能
(2)this.isInterrupted():判斷線程是否已經中斷
下邊我們來舉個例子:
(1)interrupted()方法的使用:
創建一個線程類 MyThread.java
public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 50000; i++) { System.out.println("i="+(i+1)); } } } 類Run.java
public class Run { public static void main(String[] args) { try{ MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); thread.interrupt(); //Thread.currentThread().interrupt(); System.out.println("是否停止1? = " +thread.interrupted()); System.out.println("是否停止2? = " +thread.interrupted()); }catch (InterruptedException e){ System.out.println("main catch"); } System.out.println("end!"); } }運行結果如圖
分析一下,從打印的結果來看,線程並未停止,這也就證明了interrupt()方法的解釋,判斷當前線程是否中斷,這個“當前線程”
是main,它從未中斷過,所以打印了兩個false
如何使main中斷線程呢,創建Run2.java
public class Run2 { public static void main(String[] args) { try{ Thread.currentThread().interrupt(); System.out.println("是否停止1? = " +Thread.interrupted()); System.out.println("是否停止2? = " +Thread.interrupted()); }catch (InterruptedException e){ System.out.println("main catch"); } System.out.println("end!"); } }運行結果如圖
從當前結果來看,方法interrupted()的確是判斷當前線程是否是停止狀態,但爲什麼第二個
布爾值是false呢?看一下官方的解釋:
測試當前線程是否已經中斷,線程的中斷狀態由該方法清除。換句話說,如果連續兩次調用該方法,則第二次
調用返回false(因爲這個方法不但可以判斷當前線程是否已經中斷,而且還把中斷狀態清除了),所以,第一次
調用就把中斷狀態清除了,第二次調用當然是false;
(2)
isInterrupted()方法:
isInterrupted()方法和interrupted()方法的區別就是isIterrupted()沒有清除功能並且判斷線程是否中斷
注意:沒有“當前”這兩個字