自定义实现读写锁

112 阅读1分钟
package oauthWeixin.ThreadDemo;

/**
 * @ClassName ReadWriteLock
 * @Description 读写锁
 * @Author moran
 * @Date 2020/4/19 17:13
 **/
public class ReadWriteLock {

    private int readingReaders = 0;

    private int waitingReaders = 0;

    private int writingWriters = 0;

    private int waitingWriters = 0;

    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.writingWriters>0){
                this.wait();
            }
            this.writingWriters++;
        }finally {
            this.waitingWriters--;
        }
    }

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