2013-09-22 21 views
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()「。請幫助我解決這個問題。

回答

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類庫提供了兩者的完美實現。

+0

感謝您回覆斯蒂芬,我實際上做了您上面寫的內容,但是可以保證我所做的鎖定實現將會工作,因爲沒有原子操作,如果您可以指出其他錯誤,它會很好。還要考慮到我需要在我的數據結構上實現粗粒讀/寫鎖,那麼這個實現是否適合該定義? – AnkitSablok

+0

我看不到您的鎖類中有任何錯誤。但這不是你問的。如果你確實想要一個代碼審查,你應該發佈到codereview.stackexchange.com,而不是在這裏。 –

+0

好的,謝謝你告訴我的鎖類中沒有錯誤,但是這對於多線程鏈接列表的工作是我所問的,其中多個線程正在競爭讀取和寫入。 – AnkitSablok