基于synchronized实现读写锁
昨天面试小米基础平台,面试官问了一个这样的题目,让我自己实现一个读写锁,用lock实现。想了半天lock不会,最后改用synchronized实现
- 读写锁类的实现
- 两个变量read、write记录读锁和写锁的个数
- synchronized锁会锁住一个实例,同时只能等待一个方法执行完才能执行下一个方法操作。
class MyReadWriteLock{
private volatile int read;
private volatile int write;
public MyReadWriteLock(){
this.read = 0;
this.write = 0;
}
public synchronized void readLock() throws InterruptedException{
if(write>0){
wait();
}
read++;
}
public synchronized void readUnLock(){
read--;
notifyAll();
}
public synchronized void writeLock() throws InterruptedException{
if(read>0||write>0){
wait();
}
write++;
}
public synchronized void writeUnLock(){
write--;
notifyAll();
}
}