3 回答

TA貢獻1815條經驗 獲得超13個贊
提示:
你需要一個互斥鎖;例如原始對象鎖。
您需要一個當前持有邏輯讀鎖的讀者數量的計數器。
您需要一個標志來說明編寫器是否持有邏輯寫鎖。
當且僅當您正在獲取或釋放邏輯鎖時,您才持有互斥鎖。一旦獲得它,就釋放互斥量。
您將需要使用
wait
和notify
。
實際上,您需要1實施簡化版本ReadWriteLock
。
1 - ... 為了你的家庭作業(yè)。在真實世界的程序中,您應該簡單地使用現有的ReadWriteLock
類。

TA貢獻1856條經驗 獲得超11個贊
在這里回答您更新的代碼是您需要完成的一些框架:
public class SharedResource {
private final Object signal = new Object();
private boolean writeLocked;
private int readerCount;
public void write(final Object newState) throws InterruptedException {
this.acquireWriteLock();
try {
// Now we know that no read and no other write is going on.
System.out.println("Write thread has the lock.");
this.doWrite(newState);
} finally {
// make sure we release the lock in any case.
this.realeaseWriteLock();
}
}
private void acquireWriteLock() throws InterruptedException {
synchronized (this.signal) {
// Wait until no more readers *and* no writer holds the lock.
// To do: Insert the condition we need to wait for:
while (/* condition here! */ ) {
// To do: Wait for the lock-holding thread(s) to signal that they released their lock(s).
}
this.writeLocked = true; // Let others know that the write lock has been taken.
}
}
private void realeaseWriteLock() {
synchronized (this.signal) {
this.writeLocked = false;
// To do: Notify any and all other waiting threads that we released the lock!
}
}
public Object read() {
// To be done...
}
private void acquireReadLock() throws InterruptedException {
synchronized (this.signal) {
// Wait until no *writer* holds the lock.
// To do: Insert condition we need to wait for:
while (/* condition here! */ ) {
// To do: Wait for the lock-holding thread(s) to signal that they released their lock(s).
}
// Now we know that no writer holds the lock. Acquire (another) read lock:
this.readerCount++;
}
}
private void releaseReadLock() throws InterruptedException {
synchronized (this.signal) {
this.readerCount--;
// To do: Notify any threads waiting (i.e. writer threads).
// (In fact only *required* if there are *no* more readers now because that's the only condition any thread will wait on.)
}
}
private void doWrite(final Object newState) {
// do stuff
}
private Object doRead() {
return "";
}
}
要理解的要點可能是每次嘗試獲取鎖都可能必須wait,并且每次釋放鎖都應該有notify任何(潛在的)等待線程。

TA貢獻1828條經驗 獲得超3個贊
此外,我正在考慮使用布爾標志,例如 canReadContinue
你在正確的軌道上。但是請記住,任何數量的線程都可以同時執(zhí)行它們的讀取訪問,并且只有在當前沒有其他線程正在讀取或寫入的情況下才能進行寫入訪問。
所以你需要跟蹤當前有多少讀者持有鎖,并且每個讀者都必須確保在完成后釋放鎖。只有當 0 個讀者(和 0 個寫者)持有鎖時,一個寫者才可以繼續(xù);并且僅當 & 當 0 個寫入者持有鎖時,任何讀取者都可以繼續(xù)。
添加回答
舉報