您的位置 首页 java

Java线程中断的正确姿势

1、为什么废弃Thread的stop函数?

对于有多线程开发经验的开发者,应该大多数在开发过程中都遇到过这样的需求,就是在某种情况下,希望立即停止一个线程。

比如:做Android APP开发,当打开一个界面时,需要开启线程请求网络获取界面的数据,但有时候由于网络特别慢,用户没有耐心等待数据获取完成就将界面关闭,此时就应该立即停止线程任务,不然一般会 内存泄露 ,造成系统资源浪费,如果用户不断地打开又关闭界面,内存泄露会累积,最终导致内存溢出,APP闪退。

可能有不少开发者用过Thread的stop去停止线程,当然此函数确实能停止线程,不过Java官方早已将它废弃,不推荐使用,这是为什么?

  1. stop是通过立即抛出ThreadDeath异常,来达到停止线程的目的,此异常抛出有可能发生在任何一时间点,包括在catch、finally等语句块中,但是此异常并不会引起程序退出(笔者只测试了Java8)。
  2. 由于有异常抛出,导致线程会释放全部所持有的锁,极可能引起线程安全问题。

由于以上2点,stop这种方式停止线程是不安全的。

下面是stop的源码(Java8):

 @Deprecated
 public final void stop() {
 SecurityManager security =  System .getSecurityManager();
 if (security != null) {
 checkAccess();
 if (this !=  thread .currentThread()) {
 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
 }
 }
 // A zero status value corresponds to "NEW", it can't change to
 // not-NEW because we hold the lock.
 if (threadStatus != 0) {
 resume(); // Wake up thread if it was suspended; no-op otherwise
 }
 // The VM can handle all thread states
 stop0(new ThreadDeath());
 }
 
 private native void stop0(Object o);
 

上述源码中关键代码就是stop0(new ThreadDeath())函数,这是Native函数,传递的参数是ThreadDeath,ThreadDeath是一个异常对象,该对象从Native层抛到了Java层,从而导致线程停止,不过此异常并不会引起程序退出。

很多时候为了保证数据安全,线程中会编写同步代码,如果当线程正在执行同步代码时,此时调用stop,引起抛出异常,导致线程持有的锁会全部释放,此时就不能确保数据的安全性,出现无法预期的错乱数据,还有可能导致存在需要被释放的资源得不到释放,引发内存泄露。所以用stop停止线程是不推荐的。

2、用Thread的interrupt结束线程

其实调用Thread对象的interrupt函数并不是立即中断线程,只是将线程中断状态标志设置为true,当线程运行中有调用其阻塞的函数(Thread.sleep,Object.wait,Thread.join等)时,阻塞函数调用之后,会不断地轮询检测中断状态标志是否为true,如果为true,则停止阻塞并抛出InterruptedException异常,同时还会重置中断状态标志;如果为 false ,则继续阻塞,直到阻塞正常结束。

因此,可以利用这种中断机制来控制结束线程的运行。只要理解机制,代码的实现其实比较简单。

2.1、结束未使用阻塞函数的线程

public class Main {
 public static void main(String[] args) {
 InnerClass innerClass = new InnerClass();
 Thread thread = new Thread(innerClass);
 thread.start();
 long i = System.currentTimeMillis();
 while (System.currentTimeMillis() - i < 10 * 1000) {
 thread.isAlive();
 }
 thread.interrupt();
 }
 static class InnerClass implements Runnable {
 @Override
 public void run() {
 System.err.println("start work");
 while (!Thread.currentThread().isInterrupted()) {
 System.out.println("doing work");
 }
 System.err.println("done work");
 }
 }
}
 

思路其实就是用isInterrupted来判断线程是否处于中断状态,若是中断状态,则跳出正在执行的任务,使线程结束运行。

2.2、结束使用阻塞函数的线程

public class Main {
 public static void main(String[] args) {
 InnerClass innerClass = new InnerClass();
 Thread thread = new Thread(innerClass);
 thread.start();
 long i = System.currentTimeMillis();
 while (System.currentTimeMillis() - i < 10 * 1000) {
 thread.isAlive();
 }
 thread.interrupt();
 }
 static class InnerClass implements Runnable {
 @Override
 public void run() {
 System.err.println("start work");
 while (!Thread.currentThread().isInterrupted()) {
 System.out.println("doing work");
 try {
 Thread.sleep(1000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 Thread.currentThread().interrupt();
 }
 }
 System.err.println("done work");
 }
 }
}
 

思路同2.1,需要注意的是,调用sleep函数触发InterruptedException异常时,在catch代码块中需调用interrupt函数,使线程再次处于中断状态,使while循环条件为false,使线程跳出循环,结束运行。若不调用,while循环为死循环,线程无法结束。

2.3、关于Thread的静态函数interrupted与Thread的对象函数isInterrupted

先对比下2函数的源码:

 public static boolean interrupted() {
 return currentThread().isInterrupted(true);
 }
 public boolean isInterrupted() {
 return isInterrupted(false);
 }
 /**
 * Tests if some Thread has been interrupted. The interrupted state
 * is reset or not based on the value of ClearInterrupted that is
 * passed.
 */ private native boolean isInterrupted(boolean ClearInterrupted);
 

从源码中可以看出,2函数都是调用了Native函数private native boolean isInterrupted(boolean ClearInterrupted);,前者调用传的参数为true,所以,调用interrupted函数,会在检测线程中断状态标志是否为true后,还会将中断状态标志重置为false。而isInterrupted函数只是检测线程中断状态标志。

文章来源:智云一二三科技

文章标题:Java线程中断的正确姿势

文章地址:https://www.zhihuclub.com/171707.shtml

关于作者: 智云科技

热门文章

网站地图