为何java里的Thread类的方法suspend()和resume()不推荐使用?

官方解释如下: http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html  
Why are Thread.suspend and Thread.resume deprecated?  
Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. 

Thread.suspend方法是天生易发生死锁的。 
如果要suspend的目标线程对一个重要的系统资源持有锁,那么没任何线程可以使用这个资源直到要suspend的目标线程被resumed。 

如果一条线程将去resume目标线程之前尝试持有这个重要的系统资源再去resume目标线程,这两条线程就相互死锁了。 


suspend()和resume()
suspend()方法在线程挂起时,并不释放对象锁,因此可能会导致死锁。

替代实现:

class ThreadA implements Thread {
    private boolean theadSuspend;

    public void suspendThread() {
            threadSuspend = true;
    }

    public void resumeThread() {
            synchronized(this) {
                    threadSuspend = false;
                    notify();

            }
    }

    public void run() {
            while (true) {
                    synchronized (this) {
                            while (!threadSuspend)
                                    wait();
                    }


                    doSomething();
            }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值