JAVA 多线程--interrupt()和线程终止 深入分析JAVA 多线程--interrupt()和线程终止方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JAVA 多线程--interrupt()和线程终止 深入分析JAVA 多线程--interrupt()和线程终止方式

凌倾-学无止境   2021-04-22 我要评论

一、interrupt() 介绍

interrupt() 定义在 Thread 类中,作用是中断本线程

本线程中断自己是被允许的;其它线程调用本线程的 interrupt() 方法时,会通过 checkAccess() 检查权限。这有可能抛出 SecurityException 异常。
如果本线程是处于阻塞状态:调用线程的 wait() , wait(long) 或 wait(long, int) 会让它进入等待(阻塞)状态,或者调用线程的 join(),join(long),join(long, int),sleep(long),sleep(long, int) 也会让它进入阻塞状态。若线程在阻塞状态时,调用了它的 interrupt() 方法,那么它的“中断状态”会被清除并且会收到一个 InterruptedException 异常。例如,线程通过 wait() 进入阻塞状态,此时通过 interrupt() 中断该线程;调用 interrupt() 会立即将线程的中断标记设为 true,但是由于线程处于阻塞状态,所以该“中断标记”会立即被清除为 “false”,同时,会产生一个 InterruptedException 的异常。
如果线程被阻塞在一个 Selector 选择器中,那么通过 interrupt() 中断它时;线程的中断标记会被设置为 true,并且它会立即从选择操作中返回。
如果不属于前面所说的情况,那么通过 interrupt() 中断线程时,它的中断标记会被设置为 true。
中断一个“已终止的线程”不会产生任何操作。

二、线程终止方式

Thread中的 stop() 和 suspend() 方法,由于固有的不安全性,已经建议不再使用!
下面,我先分别讨论线程在“阻塞状态”和“运行状态”的终止方式,然后再总结出一个通用的方式。

(一)、终止处于“阻塞状态”的线程.

通常,我们通过“中断”方式终止处于“阻塞状态”的线程。
当线程由于被调用了 sleep(),,wait(),join() 等方法而进入阻塞状态;若此时调用线程的 interrupt() 将线程的中断标记设为 true。由于处于阻塞状态,中断标记会被清除,同时产生一个InterruptedException 异常。将 InterruptedException 放在适当的位置就能终止线程,形式如下:

public void run() {
  try {
    while (true) {
      // 执行业务
    }
  } catch (InterruptedException ie) { 
    // 由于产生InterruptedException异常,退出while(true)循环,线程终止!
  }
}

说明:

在while(true)中不断的执行业务代码,当线程处于阻塞状态时,调用线程的 interrupt() 产生 InterruptedException 中断。中断的捕获在 while(true) 之外,这样就退出了 while(true) 循环!

注意:

对 InterruptedException 的捕获务一般放在 while(true) 循环体的外面,这样,在产生异常时就退出了 while(true) 循环。否则,InterruptedException 在 while(true) 循环体之内,就需要额外的添加退出处理形式如下:

public void run() {
  while (true) {
    try {
      // 执行任务...
    } catch (InterruptedException ie) { 
      // InterruptedException在while(true)循环体内。
      // 当线程产生了InterruptedException异常时,while(true)仍能继续运行!需要手动退出
      break;
    }
  }
}

说明:

上面的 InterruptedException 异常的捕获在 whle(true) 之内。当产生 InterruptedException 异常时,被 catch 处理之外,仍然在 while(true) 循环体内;要退出 while(true) 循环体,需要额外的执行退出while(true) 的操作。

(二)、终止处于“运行状态”的线程

通常,我们通过“标记”方式终止处于“运行状态”的线程。其中,包括“中断标记”和“额外添加标记”。

1、通过“中断标记”终止线程

public void run() {
  while (!isInterrupted()) {
    // 执行任务...
  }
}

说明:

isInterrupted() 是判断线程的中断标记是不是为 true。当线程处于运行状态,并且我们需要终止它时;可以调用线程的 interrupt() 方法,使用线程的中断标记为 true,即 isInterrupted() 会返回true。此时,就会退出while循环。

注意:interrupt() 并不会终止处于“运行状态”的线程!它会将线程的中断标记设为 true。

2、通过“额外添加标记”终止线程

private volatile boolean flag= true;
protected void stopTask() {
  flag = false;
}
public void run() {
  while (flag) {
    // 执行任务...
  }
}

说明:

线程中有一个 flag 标记,它的默认值是 true;并且我们提供 stopTask() 来设置 flag 标记。当我们需要终止该线程时,调用该线程的 stopTask() 方法就可以让线程退出 while 循环。

注意:将 flag 定义为 volatile 类型,是为了保证 flag 的可见性。即其它线程通过 stopTask() 修改了 flag 之后,本线程能看到修改后的 flag 的值。

(三)、通过方式

综合线程处于“阻塞状态”和“运行状态”的终止方式,比较通用的终止线程的形式如下:

public void run() {
  try {
    // 1. isInterrupted()保证,只要中断标记为true就终止线程。
    while (!isInterrupted()) {
      // 执行任务...
    }
  } catch (InterruptedException ie) { 
    // 2. InterruptedException异常保证,当InterruptedException异常产生时,线程被终止。
  }
}

1、isInterrupted()保证,只要中断标记为 true 就终止线程。
2、InterruptedException 异常保证,当 InterruptedException 异常产生时,线程被终止。

三、示例

public class InterruptTest {
  public static void main(String[] args) {
    try {
      Thread t1 = new MyThread("t1"); // 新建线程t1
      System.out.println(t1.getName() + "[" + t1.getState() + "] is new.");
      
      t1.start();// 启动线程t1
      System.out.println(t1.getName() + "[" + t1.getState() + "] is started.");
      
      Thread.sleep(300);// 休眠300毫秒,然后主线程给t1发“中断”指令,查看t1状态
      t1.interrupt();
      System.out.println(t1.getName() + "[" + t1.getState() + "] is interrupted.");
      
      Thread.sleep(300);// 休眠300毫秒,然后查看t1状态
      System.out.println(t1.getName() + "[" + t1.getState() + "] is interrupted now.");
    }catch(InterruptedException e) {
      e.printStackTrace();
    }
  }
}
class MyThread extends Thread{
  public MyThread(String name) {
    super(name);
  }
  @Override
  public void run() {
    try {
      int i = 0;
      while(!isInterrupted()) {
        Thread.sleep(100);// 休眠100毫秒
        ++i;
        System.out.println(Thread.currentThread().getName() + "[" + this.getState() + "] loop " + i);
      }
    }catch(InterruptedException e) {
      System.out.println(Thread.currentThread().getName() + "[" + this.getState() + "] catch InterruptedException");
    }
  }
}

运行结果

t1 [ NEW ] is new.
t1 [ RUNNABLE ] is started.
t1 [ RUNNABLE ] loop 1
t1 [ RUNNABLE ] loop 2
t1 [ RUNNABLE ] loop 3
t1 [ RUNNABLE ] catch InterruptedException
t1 [ TERMINATED ] is interrupted.
t1 [ TERMINATED ] is interrupted now.

说明:

①、主线程 main 中通过 new MyThread("t1") 创建线程 t1,之后通过 t1.start() 启动线程 t1。

②、t1 启动之后,会不断的检查它的中断标记,如果中断标记为“false”;则休眠 100ms。

③、t1 休眠之后,会切换到主线程main;主线程再次运行时,会执行t1.interrupt()中断线程t1。t1收到中断指令之后,会将t1的中断标记设置“false”,而且会抛出 InterruptedException 异常。在 t1 的 run() 方法中,是在循环体 while 之外捕获的异常;因此循环被终止。

我们对上面的结果进行小小的修改,将run()方法中捕获InterruptedException异常的代码块移到while循环体内。

public class InterruptTest {
  public static void main(String[] args) {
    try {
      Thread t1 = new MyThread("t1"); // 新建线程t1
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is new.");
      
      t1.start();// 启动线程t1
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is started.");
      
      Thread.sleep(300);// 休眠300毫秒,然后主线程给t1发“中断”指令,查看t1状态
      t1.interrupt();
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is interrupted.");
      
      Thread.sleep(300);// 休眠300毫秒,然后查看t1状态
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is interrupted now.");
    }catch(InterruptedException e) {
      e.printStackTrace();
    }
    
  }
}
class MyThread extends Thread{
  public MyThread(String name) {
    super(name);
  }
  @Override
  public void run() {
    int i = 0;
    while(!isInterrupted()) {
      try {
        Thread.sleep(100); // 休眠100ms
      } catch (InterruptedException ie) { 
        System.out.println(Thread.currentThread().getName() +" [ "+this.getState()+" ] catch InterruptedException."); 
      }
      i++;
      System.out.println(Thread.currentThread().getName()+" [ "+this.getState()+" ] loop " + i); 
    }
  }
}

运行结果

t1 [ NEW ] is new.
t1 [ RUNNABLE ] is started.
t1 [ RUNNABLE ] loop 1
t1 [ RUNNABLE ] loop 2
t1 [ TIMED_WAITING ] is interrupted.
t1 [ RUNNABLE ] catch InterruptedException.
t1 [ RUNNABLE ] loop 3
t1 [ RUNNABLE ] loop 4
t1 [ RUNNABLE ] loop 5
t1 [ RUNNABLE ] loop 6
t1 [ RUNNABLE ] is interrupted now.
t1 [ RUNNABLE ] loop 7
...... // 无限循环

说明:

程序进入了死循环了。

这是因为,t1在“等待(阻塞)状态”时,被 interrupt() 中断;此时,会清除中断标记(即 isInterrupted() 会返回 false),而且会抛出 InterruptedException 异常(该异常在while循环体内被捕获)。因此,t1理所当然的会进入死循环了。

解决该问题,需要我们在捕获异常时,额外的进行退出 while 循环的处理。例如,在 MyThread 的 catch(InterruptedException) 中添加 break 或 return 就能解决该问题。

下面是通过“额外添加标记”的方式终止“状态状态”的线程的示例:

public class InterruptTest {
  public static void main(String[] args) {
    try {
      MyThread t1 = new MyThread("t1"); // 新建线程t1
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is new.");
      
      t1.start();// 启动线程t1
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is started.");
      
      Thread.sleep(300);// 休眠300毫秒,然后主线程给t1发“中断”指令,查看t1状态
      t1.stopTask();
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is interrupted.");
      
      Thread.sleep(300);// 休眠300毫秒,然后查看t1状态
      System.out.println(t1.getName() + " [ " + t1.getState() + " ] is interrupted now.");
    }catch(InterruptedException e) {
      e.printStackTrace();
    }
    
  }
}
class MyThread extends Thread{
  private volatile boolean flag = true;
  public void stopTask() {
    flag = false;
  }
  public MyThread(String name) {
    super(name);
  }
  @Override
  public void run() {
    synchronized (this) {
      int i = 0;
      while(flag) {
        try {
          Thread.sleep(100); // 休眠100ms
        } catch (InterruptedException ie) { 
          System.out.println(Thread.currentThread().getName() +" [ "+this.getState()+" ] catch InterruptedException."); 
          break;
        }
        i++;
        System.out.println(Thread.currentThread().getName()+" [ "+this.getState()+" ] loop " + i); 
      }
    }
    
  }
}

运行结果

t1 [ NEW ] is new.
t1 [ RUNNABLE ] is started.
t1 [ RUNNABLE ] loop 1
t1 [ RUNNABLE ] loop 2
t1 [ RUNNABLE ] loop 3
t1 [ RUNNABLE ] is interrupted.
t1 [ TERMINATED ] is interrupted now.

四、interrupted() 和 isInterrupted()的区别

interrupted() 和 isInterrupted()都能够用于检测对象的“中断标记”。
区别是,interrupted() 除了返回中断标记之外,它还会清除中断标记(即将中断标记设为 false);而 isInterrupted() 仅仅返回中断标记。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们