java線程停止可以說是非常有講究的,看起來非常簡單,但是也要做好一些防范措施,一般停止一個線程可以使用Thread.stop();來實現,但是最好不要用,因為他是不安全的。
大多數停止線程使用Thread.interrupt()方法,但是這個方法不會終止一個線程,還需要加入一個判斷才可以完成線程的停止。
下面介紹一下常用停止線程應該使用的方法:
1、interrupt()
Thread.interrupt()方法僅僅設置線程的狀態位為中斷線程,並不是讓線程馬上停止,中斷線程之后會拋出interruptException異常。
2、Thread.interrupted()
測試當前線程是否已經是中斷狀態,並且清楚狀態。Boolean類型,中斷返回true,反之false。當前線程指的是當前方法,並不是啟動當前方法的線程。而清楚狀態,則是指如果調用兩次interrupted()方法,則第二次返回false。
3、Thread.isInterrupted()
測試線程是否已經是是中斷狀態,但是不清除狀態標志。
其實上面的開始我也不理解,經過多次思考,我用自己的話總結一下吧。
1、interrupt()方法僅僅將線程設置為中斷狀態,但是並不會去停止線程,返回true說明線程的中斷狀態已經被設置了。
2、
interrupt()、interrupted()和isInterrupted()的具體使用:
interrupt()、interrupted()使用:
public class Test01 extends Thread { @Override synchronized public void run() { super.run(); for (int i = 0; i < 100000; i++) { //判斷線程是否停止 if (this.interrupted()){ System.out.println("已經停止了"); break; } System.out.println(i); } System.out.println("雖然線程已經停止了,但是還是會跳出for循環繼續向下執行的"); } public static void main(String[] args) { Test01 test = new Test01(); try { test.start(); test.sleep(50); //線程停止 test.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(); } }
打印結果:
3707
3708
3709
3710
3711
已經停止了
雖然線程已經停止了,但是還是會跳出for循環繼續向下執行的
使用異常捕獲法停止多線程:
當interrupted()檢測到線程狀態為停止的時候,會拋出異常,繼而捕獲這個異常來停止多線程
/** * 使用異常捕獲法停止多線程 */ public class Test01 extends Thread { @Override synchronized public void run() { super.run(); try { for (int i = 0; i < 100000; i++) { //判斷線程是否停止 if (this.interrupted()) { System.out.println("已經停止了"); //拋出異常 throw new InterruptedException(); } System.out.println(i); } } catch (InterruptedException e) { System.out.println("線程結束..."); } } public static void main(String[] args) { Test01 test = new Test01(); try { test.start(); test.sleep(100); test.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(); } }
打印語句:
8219
8220
8221
8222
8223
8224
已經停止了
線程結束...