0

我已将读/写锁编码如下-:

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( )“ 分别。请帮我解决这个问题。

4

1 回答 1

0

例如:

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 类库提供了两者的完美实现。

于 2013-09-22T03:45:07.453 回答