用2个int实现一个简单的Java 读写锁,帮助理解读写锁的原理
/**
* 只用2个int实现一个读写锁
*
* @author Red
* date: 2019/4/27 10:20
*/
public class MyReadWriteLock {
// 读线程个数
private int readCount = 0;
// 写线程个数
private int writeCount = 0;
// 获取读锁
public void readLock() throws InterruptedException {
// 已经有写线程存在,则等待
while (writeCount > 0) {
synchronized (this) {
wait();
}
}
// 获取读锁成功
readCount++;
}
// 释放读锁
public void unReadLock() {
while (readCount > 0) {
readCount--;
synchronized (this) {
notifyAll();
}
} else {
// 释放错误
}
}
public void writeLock() throws InterruptedException {
// 写写互斥
while (writeCount > 0) {
synchronized (this) {
wait();
}
}
// 保证写锁的优先级
writeCount++;
// 读写互斥
while (readCount > 0) {
synchronized (this) {
wait();
}
}
}
// 释放写锁
public void unWriteLock() {
while (writeCount > 0) {
writeCount--;
synchronized (this) {
notifyAll();
}
} else {
// 释放错误
}
}
}