不推荐的中止方式

stop

中止线程,并且清除监控器锁的信息,可能导致线程安全文件,jdk不建议使用

举例说明如何导致线程安全问题:

先定义一个线程,实现i和j同时+1

public class StopThread extends Thread {
  private int i = 0, j = 0;

  @Override
  public void run() {
    synchronized (this) {
	    // 增加同步锁,确保线程安全
	    ++i;
	    try {
	      // 休眠10秒,模拟耗时操作
	      Thread.sleep(10000);
	    } catch (InterruptedException e) {
	      e.printStackTrace();
	    }
	    ++j;
    }
  }

  /** * 打印i和j */
  public void print() {
  System.out.println("i=" + i + " j=" + j);
  }
}

stop方式中止

/**
 * 示例3 - 线程stop强制性中止,破坏线程安全的示例
 */
public class Demo31 {
  public static void main(String[] args) throws InterruptedException {
    StopThread thread = new StopThread();
    thread.start();
    // 休眠1秒,确保i变量自增成功
    Thread.sleep(1000);
    // 暂停线程
    thread.stop(); // 错误的终止
    // thread.interrupt(); // 正确终止
    while (thread.isAlive()) {
      // 确保线程已经终止
    } // 输出结果
    thread.print();
  }
}

理想输出:i=0 j=0

实际执行结果:i=1 j=0

i没有因中止而回滚,没有保证同步代码块里面的数据一致性,破坏了线程安全

destroy

jdk未实现该方法

优雅的线程中止

interrupt

  • 如果目标线程在调用Object class的wait(),wait(long),wait(long,int)方法,join(),join(long,int)sleep(long,int)方法时被阻塞,那么interrupt会生效,该线程的中断状态将被清除,抛出InterruptedException异常

  • 如果目标线程是被I/O或者NIO中的Channel所阻塞,同样,I/O操作会被中断或者返回特殊异常值.达到终止线程的目的.

  • 如果以上条件都不满足,则会设置此线程的中断状态.

复用上面的例子,将其中的thread.stop();改为thread.interrupt();查看执行结果:

结果i=1 j=1保证了数据一致性,同时抛出一个InterruptedException异常来给开发者进行对应处理

标志位

代码逻辑中,增加一个判断,用来控制线程的中止.

如下示例,设置一个flag,通过外部修改flag的值来让while条件不满足跳出循环以使线程继续运行到结束:

/** 通过状态位来判断 */
public class Demo4 extends Thread {
  public volatile static boolean flag = true;

  public static void main(String[] args) throws InterruptedException {
    new Thread(() -> {
      try {
        while (flag) { // 判断是否运行
          System.out.println("运行中");
          Thread.sleep(1000L);
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
    // 3秒之后,将状态标志改为False,代表不继续运行
    Thread.sleep(3000L);
    flag = false;
    System.out.println("程序运行结束");
  }
}