java停止線程


停止線程

停止線程需要一定的技巧。需要做好防范措施,避免“線程不安全”。

  1. 使用Thread.interrupt()

使用interrupt停止線程

原理

對線程隊形調用interrupt()方法,這個方法僅僅是給線程打一個停止狀態的標記,並不會真正停止。

可以通過條件判斷檢驗這個標記后,主動拋出異常並停止線程或后直接return,可以稱之為異常法和return法。

判斷interrupt標志:

Thread.java提供了兩種方法。

  1. 靜態方法Thread.interrupted()
  2. 線程對象的方法example.isInterrupted(),example是線程實例。

兩者區別:兩者都可以判斷是否處於停止狀態(或者說是否含有interrulted標志,更容易理解),但是Thread.interrupted()還具有清除狀態標志的功能。

假設線程a 被打入了interrupted標志,那么如果連續調用兩次example.isInterrupted(),返回的是true,true

而連續兩次調用Thread.interrupted(),返回的則是true、false,這是因為第二次調用Thread.interrupted()的時候,interrupted狀態已經被第一次重置了。

A、拋出異常法

(1)運行狀態下打入interrupted標志

繼承Thread創建MyThread3,遇見interrupted標志后主動拋出InterruptedException。

package foreverly.cn.chapter1;

public class MyThread3 extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 5000; i++) {
//					檢測是否含有interrupted標志
                if (this.isInterrupted()) {
                    System.out.println("打入了interrupted標志");
                    System.out.println("這只是個標志,並不會直接停止運行");
//                拋出異常法
                    throw new InterruptedException();
                }
                System.out.println("i=" + i);
            }
//			驗證線程確實終止            
            System.out.println("我在for下面,不會被執行");
        } catch (InterruptedException e) {
            System.out.println("主動拋出的異常被抓住了");
            e.printStackTrace();
        }
    }
}

測試Test3.java

package foreverly.cn.chapter1;

public class Test3 {
    public static void main(String[] args) {
        try {
            MyThread3 thread = new MyThread3();
            thread.start();
            Thread.sleep(10);
            thread.interrupt();
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("進入main線程的catch,作用於Thread.sleep(2000)");
            e.printStackTrace();
        }
        System.out.println("main線程結束");
    }
}

輸出結果:

i=1
i=2
......
i=193
i=194
i=195
打入了interrupted標志
這只是個標志,並不會直接停止運行
主動拋出的異常被抓住了
java.lang.InterruptedException
	at foreverly.cn.chapter1.MyThread3.run(MyThread3.java:13)
main線程結束

for循環到i=195的時候被打入了interrupted標志,通過 if (this.isInterrupted())判斷含有interrupted標志,於是throw new InterruptedException()主動拋出異常並捕獲,實現了線程的終止。

當sleep與遇上了interrupted

上面討論的是運行狀態下的線程通過interrupted標志。如果sleep狀態的線程被打上interrupted 標記時,或者被interrupted標志的線程調用sleep,會發生什么呢?

(1)先sleep后被打上interrupted標志

package foreverly.cn.chapter1;

public class MyThread2 extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run begin");
//           讓此線程sleep足夠時間
            Thread.sleep(200000000);
            System.out.println("這里不會執行");
        } catch (InterruptedException e) {
            System.out.println("在sleep中進入catch");
            e.printStackTrace();
        }
    }

}

package foreverly.cn.chapter1;

public class TestMain2 {
   public static void main(String[]  args) {
      MyThread2 thread = new MyThread2();
      thread.start();
//    讓主線程sleep一段時間,保證thread線程可以進入sleep狀態。
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      thread.interrupt();
      System.out.println("main end");
      
   }

}
run begin
main end
在sleep中進入catch
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at foreverly.cn.chapter1.MyThread2.run(MyThread2.java:9)

注意,這里的異常並非主動拋出,說明當sleep狀態的線程被打入interrupted時,會立即拋出java.lang.InterruptedException:sleep interrupted

(2)先打上interrupted標記后進入sleep

package foreverly.cn.chapter1;

public class MyThread2 extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run begin");
           while (true) {
               if (this.isInterrupted()){
                   System.out.println("thread線程被打入interrupted標志");
                   break;
               }
               System.out.println("thread運行中...");
           }
            Thread.sleep(20000);
            System.out.println("run end");
        } catch (InterruptedException e) {
            System.out.println("先interrupt,在遇到sleep,進入catch");
            e.printStackTrace();
        }
    }

}
package foreverly.cn.chapter1;

public class TestMain2 {
   public static void main(String[]  args) {
      MyThread2 thread = new MyThread2();
      thread.start();
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      thread.interrupt();
      System.out.println("main end");
      
   }

}

輸出:

thread運行中...
thread運行中...
thread運行中...
thread運行中...
thread運行中...
......
thread運行中...
thread運行中...
thread運行中...
thread運行中...
thread運行中...
thread線程被打入interrupted標志
main end
先interrupt,在遇到sleep,進入catch
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at foreverly.cn.chapter1.MyThread2.run(MyThread2.java:16)

綜上可知:會立即拋出java.lang.InterruptedException: sleep interrupted

B、return法

將上述拋出異常並捕獲,改為直接return。

更推薦使用異常法,拋出異常可以實現程序的分流,更好的控制程序,而過多的return會污染程序。

C、stop暴力停止

這個方法太暴力了,所以被廢棄了。

當對一個線程對象調用stop方法時,線程會立刻停止。(並且會拋出java.lang.ThreadDeath異常,但通常此異常不需要顯示捕捉。)

說其暴力,是因為調用后立刻停止,很容易造成數據不同步。

舉個例子,線程a的run方法用來改變用戶名和密碼,並未為了保證線程安全,避免同步修改使用了synchronized。可是,當線程運行時,改變了用戶名,此時CPU資源切換到線程b,線程b中通過a.stop()把線程a暴力停止了,那么線程a只修改了用戶名,卻沒修改密碼。

所以stop被廢棄。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM