当一个线程进入wait之后
就必须等其他线程notify/notifyall
使用notifyall
可以唤醒
所有处于wait状态的线程使其重新进入锁的争夺队列中而notify只能唤醒一个注意任何时候只有一个线程可以获得锁也就是说只有一个线程可以运行synchronized 中的代码notifyall只是让处于wait的线程重新拥有锁的争夺权但是只会有一个获得锁并执行
那么notify和notifyall在效果上又什么实质区别呢?
主要的效果区别是notify用得不好容易导致死锁例如下面提到的例子
public synchronized void put(Object o) {
while (bufsize()==MAX_SIZE) {
wait() // called if the buffer is full (try/catch removed for brevity)
}
bufadd(o)
notify() // called in case there are any getters or putters waiting
}
public synchronized Object get() {
// Y: this is where C tries to acquire the lock (ie at the beginning of the method)
while (bufsize()==) {
wait() // called if the buffer is empty (try/catch removed for brevity)
// X: this is where C tries to reacquire the lock (see below)
}
Object o = bufremove()
notify() // called if there are any getters or putters waiting
return o;
}所以除非你非常确定notify没有问题大部分情况还是是用notifyall