為何java裡的Thread類的方法suspend()和resume()不推薦使用?
阿新 • • 發佈:2019-02-18
官方解釋如下: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。
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();
}
}
}