Java线程之Read-Write Lock Pattern

Read-Write Lock Pattern的参与者:

1. Reader(读取者)参与者

    Reader参与者会对SharedResource参与者进行read。

2. Writer(写入者)参与者

    Writer参与者会对SharedResource参与者进行write。

3. SharedResource(共享资源)参与者

    SharedResource参与者代表Reader与Writer所共享的资源。

    SharedResource参与者会提供不会改变内部状态的操作(read)和会改变内部状态的操作(write)。

4. ReadWriteLock(读写用锁定)参与者

    ReadWriteLock参与者提供了对SharedResource参与者进行read操作与进行write操作时需要的锁定。

    为了完成read操作,提供了readLock与readUnlock。

    为了完成write操作,提供了writeLock和writeUnlock。

 

------------------------------

Read-Write Lock Pattern适合读取比写入次数频繁的情况。

Read-Write Lock Pattern李永乐读取操作彼此之间不会冲突的特性,使得多个Reader参与者可以同时进行read,以提升程序的性能。

不过当写入操作频率较高时,Writer参与者会经常阻拦Reader参与者的read操作的进行,这样也就无法展现Read-Write Lock Pattern的优点了。

------------------------------

一个 ReadWriteLock参与者的实现:

public final class ReadWriteLock{ private int readingReaders = 0; // 实际正在读取的线程数 private int waitingWriters = 0; // 正在等待写入的线程数 private int writingWriters = 0; // 实际正在写入的线程数 private boolean preferWriter = true; // 是否写入优先 public synchronized void readLock() throws InterruptedException{ while(writingWriters >0 ||(preferWriter && waitingWriters >0)){ wait(); } readingReaders++; } public synchronized void readUnlock() throws InterruptedException{ readingReaders--; notifyAll(); } public synchronized void writeLock() throws InterruptedException{ waitingWriters++; try{ while(readingReaders>0||writingWriters>0){ wait(); } }finally{ waitingWriters--; } writingWriters++; } public synchronized void writeUnlock() throws InterruptedException{ writingWriters--; notifyAll(); } }

你可能感兴趣的:(java,Class)