有一个共享资源,我们需要按照以下方式对其执行读/写操作:
当对资源进行写入时,不应允许读取。
当读取正在进行时,不允许写入,但多个读取线程应该能够读取。
我已经编写了如下所述的代码,但此代码的问题是当单个读取线程已获取锁时,所有读取都将被阻止。此外,我正在考虑使用布尔标志,例如 canReadContinue。现在,当 read 第一次获取锁时,我会将此标志翻转为 true,如果为 true,则其他线程不应尝试获取锁。
class SharedResource {
Lock writeLock
public Object read() {
writeLock.acquire()
doRead()
}
public void write(Object toBeWritten) {
writeLock.acquire()
doWrite(toBeWritten)
writeLock.release()
}
}
预期是在没有写入时多个线程应该能够读取。
更新 1:
公共类共享资源{
private Object writeLock = new Object();
private volatile boolean canReadContinue;
private volatile int readCount;
public void write(Object newState) throws InterruptedException {
synchronized (writeLock) {
// To make sure no read is going on
while (readCount > 0) {
wait();
}
System.out.println("Write thread has the lock.");
doWrite(newState);
}
}
public Object read() {
if(canReadContinue) {
incrementCount();
} else {
synchronized (writeLock) {
System.out.println("Read thread has the lock.");
canReadContinue = true;
incrementCount();
}
}
Object result = doRead();
decrementCount();
if(readCount == 0) {
// TODO - release lock and notify
}
return result;
}
private synchronized void incrementCount() {
readCount++;
}
private synchronized void decrementCount() {
readCount--;
}
private void doWrite(Object newState) {
// do stuff
}
private Object doRead() {
return "";
}
}
现在我需要一种机制来在“// TODO - 释放锁并通知”行释放锁,任何指针如何解决这个问题?
萧十郎
呼唤远方
倚天杖
相关分类