关于读写锁模式需要明白几个要素
1、写:当前没有写操作,以及没有读操作
2、读:当前没有写操作
package com.puqiuyu.thread.blog.pattern;
/**
*
*
* @author sunday
*
*/
public class WriteAndReadLock {
// 正在写的线程
private int writings;
// 等待写的线程
private int waitWrites;
// 正在读的线程
private int readings;
//定义写优先
private boolean writePre;
public WriteAndReadLock() {
this(true);
}
public WriteAndReadLock(boolean writePre) {
this.writePre = writePre;
}
public synchronized void readLock() throws InterruptedException {
//当有写锁加入等待时,读锁排在其后。
while (writings > 0 || (writePre && waitWrites > 0)) {
this.wait();
}
readings++;
}
public synchronized void unReadLock() {
this.notifyAll();
readings--;
}
public synchronized void writeLock() throws InterruptedException {
try {
//有写或者有读都堵塞
while (writings > 0 || readings > 0) {
waitWrites++;
this.wait();
}
writings++;
} finally {
waitWrites--;
}
}
public synchronized void unWriteLock() {
writings--;
this.notifyAll();
}
}
简单分析下
1、写锁时需要判断是否有其他写锁占用,同时需要判断是否有读操作占用。如果有等待。
2、读锁时,需要判断是否有写锁占用。
为了保证写优先,单其他写锁加入后,之后读锁都等待。