zoukankan      html  css  js  c++  java
  • Java线程中断的理解和正确使用

    Java线程中断的理解和正确使用

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

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

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

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

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

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

    下面是stop的源码(Java8):

    1. @Deprecated
    2. public final void stop() {
    3. SecurityManager security = System.getSecurityManager();
    4. if (security != null) {
    5. checkAccess();
    6. if (this != Thread.currentThread()) {
    7. security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
    8. }
    9. }
    10. // A zero status value corresponds to "NEW", it can't change to
    11. // not-NEW because we hold the lock.
    12. if (threadStatus != 0) {
    13. resume(); // Wake up thread if it was suspended; no-op otherwise
    14. }
    15. // The VM can handle all thread states
    16. stop0(new ThreadDeath());
    17. }
    18. 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、结束未使用阻塞函数的线程

    1. public class Main {
    2. public static void main(String[] args) {
    3. InnerClass innerClass = new InnerClass();
    4. Thread thread = new Thread(innerClass);
    5. thread.start();
    6. long i = System.currentTimeMillis();
    7. while (System.currentTimeMillis() - i < 10 * 1000) {
    8. thread.isAlive();
    9. }
    10. thread.interrupt();
    11. }
    12. static class InnerClass implements Runnable {
    13. @Override
    14. public void run() {
    15. System.err.println("start work");
    16. while (!Thread.currentThread().isInterrupted()) {
    17. System.out.println("doing work");
    18. }
    19. System.err.println("done work");
    20. }
    21. }
    22. }

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

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

    1. public class Main {
    2. public static void main(String[] args) {
    3. InnerClass innerClass = new InnerClass();
    4. Thread thread = new Thread(innerClass);
    5. thread.start();
    6. long i = System.currentTimeMillis();
    7. while (System.currentTimeMillis() - i < 10 * 1000) {
    8. thread.isAlive();
    9. }
    10. thread.interrupt();
    11. }
    12. static class InnerClass implements Runnable {
    13. @Override
    14. public void run() {
    15. System.err.println("start work");
    16. while (!Thread.currentThread().isInterrupted()) {
    17. System.out.println("doing work");
    18. try {
    19. Thread.sleep(1000);
    20. } catch (InterruptedException e) {
    21. e.printStackTrace();
    22. Thread.currentThread().interrupt();
    23. }
    24. }
    25. System.err.println("done work");
    26. }
    27. }
    28. }

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

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

    先对比下2函数的源码:

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

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

  • 相关阅读:
    垂直水平居中几种实现风格
    重绘(repaint)和回流(reflow)
    对象深拷贝
    PhantomJS not found on PATH
    d3.js 数据操作
    canvas 绘制圆弧
    d3.js 柱状图
    d3.js -- 比例尺 scales scaleLinear scaleBand scaleOrdinal scaleTime scaleQuantize
    d3.js -- select、selectAll
    map映射
  • 原文地址:https://www.cnblogs.com/nangonghui/p/14120049.html
Copyright © 2011-2022 走看看