java中的线程(2):如何正确停止线程之2种常见停止方式

1.常见停止方式

  • 结束run函数,run中含退出标志位。
  • 使用interrupt()方法中断线程
  • 使用stop方法暴力终止(已经弃用)

2.结束run

 1     class TestThread extends Thread{
 2         volatile boolean flag = true;
 3         @Override
 4         public void run() {
 5             while (!flag){
 6                 Log.d(TAG, "running ....");
 7             }
 8             Log.d(TAG, "thread " + getId() + " finished !");
 9             Log.d(TAG, "isAlive " + isAlive());
10         }
11         public void stopThread(){
12             flag = false;
13         }
14     }
15     TestThread testThread;
16     void stopThread(){
17         Log.d(TAG, "stopThread: isAlive : " + testThread.isAlive());
18         Log.d(TAG, "stopThread: isInterrupted : " + testThread.isInterrupted());
19 
20         testThread.stopThread();
21         Log.d(TAG, "stopThread: isAlive : " + testThread.isAlive());
22         Log.d(TAG, "stopThread: isInterrupted : " + testThread.isInterrupted());
23 
24     }
  • 调用testThread.stopThread就可以了。
  • 使用场景无限制

3.使用interrupt()方法

3.1示例

 1   class TestThread extends Thread{
 2         @Override
 3         public void run() {
 4             while (!Thread.currentThread().isInterrupted()){
 5                 Log.d(TAG, "running .... interrupt = " + this.isInterrupted());
 6                 try {
 7                     Thread.sleep(1000 * 1);
 8                 } catch (InterruptedException e) {
 9                     e.printStackTrace();
10                     Log.d(TAG, "InterruptedException interrupt is reset = " + this.isInterrupted());
11                     // Thread.sleep()方法由于中断抛出异常。
12                     // Java虚拟机会先将该线程的中断标识位清除,然后抛出InterruptedException,
13                     // 因为在发生InterruptedException异常的时候,会清除中断标记
14                     // 如果不加处理,那么下一次循环开始的时候,就无法捕获这个异常。
15                     // 故在异常处理中,再次设置中断标记位
16                     Thread.currentThread().interrupt();
17                 }
18             }
19             Log.d(TAG, "thread " + getId() + " finished !");
20             Log.d(TAG, "isAlive " + isAlive());
21         }
22     }
23     TestThread testThread;
24     void stopThread(){
25         Log.d(TAG, "stopThread: isAlive : " + testThread.isAlive());
26         Log.d(TAG, "stopThread: isInterrupted : " + testThread.isInterrupted());
27 
28         testThread.interrupt();
29         Log.d(TAG, "stopThread: isAlive : " + testThread.isAlive());
30         Log.d(TAG, "stopThread: isInterrupted : " + testThread.isInterrupted());
31 
32     }

3.1使用场景 

  适合线程处于阻塞状态,如使用了sleep,同步锁的wait,socket中的receiver,accept等方法时。

  当调用阻塞线程的interrupt()方法时,会抛出InterruptException异常。通过代码捕获该异常,然后跳出循环状态,从而让我们有机会结束这个线程的执行。

  调用interrupt方法后线程并不一定会结束, 只有捕获InterruptedException异常之后跳出循环,才能正常结束run方法。

4.Thread.stop()

  已经弃用

  http://www.cnblogs.com/sjjg/p/7625571.html

  

原文地址:https://www.cnblogs.com/mhbs/p/7625719.html