字数
98 字
阅读时间
1 分钟
下面我使用java中的管程实现了读者优先的读者写者同步策略
java
public class ReaderPriorityLock {
private int activeReaders = 0;
private boolean isWriting = false;
public synchronized void startRead() throws InterruptedException {
while (isWriting) {
wait();
}
activeReaders++;
}
public synchronized void endRead() {
activeReaders--;
if (activeReaders == 0) {
notifyAll();
}
}
public synchronized void startWrite() throws InterruptedException {
while (isWriting || activeReaders > 0) {
wait();
}
isWriting = true;
}
public synchronized void endWrite() {
isWriting = false;
notifyAll();
}
}