我在許多教程中遇到了ReadWriteLock的不可重入實現。ReadWriteLocks-(不可重入)它如何支持多讀取器獲取讀鎖
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
)的這個類在所有讀取器和寫入線程共享用於同步。
假設讀者T1調用lock.lockRead()
,這將獲取鎖對象上的鎖,同時讀者T2在同一個對象上調用lockRead()
。但是T1已經鎖定了對象,所以T2應該被阻塞並且在隊列中等待。
那麼,代碼如何讓多個讀者同時設置readLock?
請糾正我知道當我得到這個錯誤。
謝謝,這很有幫助 – Pintu