【发布时间】:2017-04-20 19:41:47
【问题描述】:
我在java 中使用wait/notify 看到了一些关于自定义read-write lock 实现的帖子。它看起来像:
public class ReadWriteLock{
private int readers;
private int writers;
private int writeRequests;
public synchronized void lockRead() throws InterruptedException{
while(writers > 0 || writeRequests > 0){
wait();
}
readers++;
}
public synchronized void unlockRead(){
readers--;
notifyAll();
}
public synchronized void lockWrite() throws InterruptedException{
writeRequests++;
while(readers > 0 || writers > 0){
wait();
}
writeRequests--;
writers++;
}
public synchronized void unlockWrite() throws InterruptedException{
writers--;
notifyAll();
}
}
我无法理解它是如何正确工作的,除非我没有正确理解 wait/notify 的真正工作原理。假设read 请求和Threads 更多,我的问题是:
-
1234563因此,
基于上面的假设和陈述,多个
read Threads怎么可能同时访问一个方法,因为他们应该首先调用lockRead(),这也是同步的?
Thread 应该首先获得锁来执行此操作(如果我没记错的话)。只要read Thread调用wait,只有writeRequests或writers大于0,write Thread怎么有机会获得锁?
【问题讨论】:
-
你的方法是对的。我测试了你的代码,它工作正常。只是我需要知道当你使用 unlockRead 和 unlockWrite 方法时?
-
wait()在它做它的时候释放锁。然后,lock*操作必须与相应的unlock*操作配对,例如rwl.lockRead(); try { /* ... */ } finally { rwl.unlockRead(); }。为什么unlockWrite声明InterruptedException?
标签: java multithreading synchronization