假设我有一个用 Java 实现的读/写监视器。
多个读取器或一个写入器可以同时访问数据库(不能同时访问)
class RWmonitor{
private int readers = 0;
private boolean writing = false;
public synchronized void StartRead(){ ..}
public synchronized void EndRead(){
notifyAll();
readers--;
}
public synchronized void StartWrite(){ ..}
public synchronized void EndWrite(){
notifyAll();
writing = false;
}
}
现在,如果 notifyAll()
不是同步方法中的最后一条语句,这有关系吗?
假设:
1) EndRead()
执行
2) notifyAll()
通知所有等待线程
3)然后它会减少读者数量。
当它执行notifyAll()
时,由于唤醒的线程将等待RWmonitor上的锁被释放,所以它的成本是否会更高? (假设拥有 RWmonitor 锁的线程仍然处于 readers--;
)
最佳答案
是否是最后一条语句并不重要。
The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.
关于java - notifyall() 不是最后一条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16342571/