我已将读/写锁编码如下-:
public class ReadWriteLocks {
private volatile int numberOfReaders = 0;
private volatile int numberOfWriters = 0;
private volatile int numberOfWriteRequests = 0;
public int getNumberOfReaders() {
return this.numberOfReaders;
}
public int getNumberOfWriters() {
return this.numberOfWriters;
}
public int getNumberOfWriteRequests() {
return this.numberOfWriteRequests;
}
public synchronized void lockRead() throws InterruptedException {
while (numberOfWriters > 0 || numberOfWriteRequests > 0)
this.wait();
// increment the number of readers
++numberOfReaders;
}
public synchronized void unlockRead() {
// decrement the number of readers
--numberOfReaders;
notifyAll();
}
public synchronized void lockWrite() throws InterruptedException {
// increase the number of write requests
++numberOfWriteRequests;
while (numberOfReaders > 0 || numberOfWriters > 0)
this.wait();
--numberOfWriteRequests;
++numberOfWriters;
}
public synchronized void unlockWrite() {
// decrement the number of writers
--numberOfWriters;
// notify all the threads
this.notifyAll();
}
}
但是如何在我的单链表类中将此锁应用于读取器和写入器方法,读取器方法是“getNthElement()”和“searchList()”,写入器方法是“insert()”和“delete( )“ 分别。请帮我解决这个问题。