如何使用ReentrantReadWriteLock等待数据?

Suz*_*ioc 5 java concurrency reentrantreadwritelock java.util.concurrent

据说,这ReentrantReadWriteLock是针对一位作家和多位读者的。

但是,读取器应该等待,直到缓冲区中存在一些数据为止。

那么,要锁定什么?

我创建了并发对象,如下所示:

private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
protected final Lock readLock = rwl.readLock();
protected final Lock writeLock = rwl.writeLock();
protected final Condition hasData = writeLock.newCondition();
Run Code Online (Sandbox Code Playgroud)

现在在写方法中,我这样做:

writeLock.lock();

// writing first portion and updating variables

hasData.signalAll();

// if required then writing second portion and updating variables

hasData.signalAll();
Run Code Online (Sandbox Code Playgroud)

但是如何写一个读者呢?它应该只获得readLock吗?但是它如何等待信号呢?如果还要求a,writeLock那么读/写锁定的最高权限在哪里?

如果必需的变量仅受的保护,如何确保它们在读取期间不会改变writeLock

问题不匹配

这是关于的问题ReentrantReadWriteLock

Gee*_*nte 6

ReentrantReadWriteLock 确实有点混乱,因为 readLock 没有条件。您必须在阅读器中升级到 writeLock 才能等待条件。

在作家。

writeLock.lock(); //locks all readers and writers
// do write data
hasData.signalAll();
writeLock.unlock();
Run Code Online (Sandbox Code Playgroud)

在阅读器中,您可以:

readLock.lock(); //blocks writers only
try{
 if(!checkData()) //check if there's data, don't modify shared variables
 {
  readLock.unlock();
  writeLock.lock(); // need to lock the writeLock to allow to use the condition.
                    // only one reader will get the lock, other readers will wait here      
  try{
   while(!checkData()) // check if there' still no data
   {
     hasData.await(); //will unlock and re-lock after writer has signalled and unlocked.
   }
   readLock.lock();    // continue blocking writer
  }
  finally
  {
    writeLock.unlock(); //let other readers in
  }
 }
 //there should be data now
 readData(); // don't modify variables shared by readers.
}
finally
{
  readlock.unlock(); //let writers in
}
Run Code Online (Sandbox Code Playgroud)

当然,为了完整起见,每个 unlock() 都应该在 finally 块中。