略坑的Thread.stop()


一,stop方法调用之后,线程的run不一定会立即结束



首先来看下stop方法的代码:


 @Deprecated
    public final synchronized void stop(Throwable obj) {
        if (obj == null)
            throw new NullPointerException();

        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            checkAccess();
            if ((this != Thread.currentThread()) ||
                (!(obj instanceof ThreadDeath))) {
                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(obj);
    }


stop方法是一个同步方法,在执行时候,会抛出ThreadDeath异常

public class StopThreadTest {


    @Test
    public void stopTest() throws InterruptedException {

        Thread t = new someThread();
        t.start();
        Thread.sleep(7);
        t.stop();

    }


    class someThread extends Thread {

        public synchronized void run() {
            for (int i = 0; i < 1000000; i++) {
                System.out.println("i=" + i);//一直全部打印完
            }
            System.out.println("打印完成!!!");
        }
    }
}


     在我们自己的实现类里面,如果将run方法改为同步方法,那么即使使用时候,调用了stop方法,由于是同步操作,必须等待run方法全部结束之后,stop才会真正被调用。


二,可能会造成逻辑上的不连贯



如果run方法是个原子操作,当调用stop方法之后,run方法未完成之前,操作就终止了,立即释放该线程持有的所有资源,可是操作只进行了一部分,就造成了逻辑上的不连贯。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水田如雅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值