1. 读写锁模式
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 (this.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.waitingWriters > 0 || this.readingReaders > 0) {
this.wait();
}
this.writingWriters++;
} finally {
this.waitingWriters--;
}
}
public synchronized void writeUnLock() {
this.writingWriters--;
this.notifyAll();
}
}