我在许多教程中都遇到了 ReadWriteLock 的不可重入实现。
public class ReadWriteLock{
private int readers = 0;
private int writers = 0;
private int writeRequests = 0;
public synchronized void lockRead() throws InterruptedException{
while(writers > 0 || writeRequests > 0){
wait();
}
readers++;
}
public synchronized void unlockRead(){
readers--;
notifyAll();
}
public synchronized void lockWrite() throws InterruptedException{
writeRequests++;
while(readers > 0 || writers > 0){
wait();
}
writeRequests--;
writers++;
}
public synchronized void unlockWrite() throws InterruptedException{
writers--;
notifyAll();
}
}
问题:
lock
此类的一个对象(例如)在所有读取器和写入器线程之间共享以进行同步。
让我们假设 Reader T1 调用lock.lockRead()
,这获得了锁对象上的锁,而 Reader T2 同时调用lockRead()
了同一个对象。但是 T1 已经锁定了对象,所以 T2 应该被阻塞并在队列中等待。
那么,代码是如何让多个阅读器同时设置readLock的呢?
请纠正我知道我什么时候弄错了。