深入理解线程中断方式

深入理解线程中断方式

为什么废弃Thread的stop函数?

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停止线程是不推荐的。

用Thread的interrupt结束线程

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

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

这两个函数的源码:

    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线程中断的正确姿势

线程中如何处理InterruptedException

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值