我已经将读/写锁编码如下 - :
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()"。 请帮我解决这个问题。
例如:
public Object getNthElement(int n) {
try {
myLock.lockRead();
// fetch element;
return element;
} catch (InterruptedException ex) {
// If you don't want this exception to propagate, then the correct
// thing to do is set the "interrupted" flag again.
Thread.interrupt(Thread.currentThread());
} finally {
myLock.unlockRead();
}
}
但是,我不确定您在这里要实现什么,无论是通过实现自定义锁类型还是通过实现您自己的链表类型。 标准 Java SE 类库提供了两者的完美实现。