【多線程】JAVA實現讀寫鎖

1. 優勢

讀寫分離鎖可以提升程序的併發讀,因爲在大多數情況下都是讀請求那麼此時讀與讀之間是可以並行執行的不會產生數據不一致問題,只有讀寫,寫寫操作纔是互斥的

2. 讀寫鎖實現

package com.gy.readwritelock;

public class ReadWriteLock {

    private int readingReaders;
    private int waitingReaders;
    private int writingWriters;
    private int waitingWriters;



    public synchronized void readLock() throws InterruptedException {
        this.waitingReaders++;
        try {
            while(writingWriters > 0) {
                this.wait();
            }
            this.readingReaders++;
        } finally {
            this.waitingReaders--;
        }
    }


    public synchronized void readUnlock() {
        this.readingReaders--;
        this.notifyAll();
    }


    public synchronized void writeLock() throws InterruptedException {
        this.waitingWriters++;

        try {
            while(this.readingReaders > 0 || this.writingWriters > 0)
                this.wait();
            this.writingWriters++;
        } finally {
            this.waitingWriters--;
        }
    }


    public synchronized void writeUnlock() {
        this.writingWriters--;
        this.notifyAll();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章