java中的同步读写器
我想实现自己的java中的同步读写器,java,multithreading,Java,Multithreading,我想实现自己的readWriteLock类,而不使用API提供的readWriteLock 我有这样的情况: public void read(){ if(!write){ read = true; //any thread can enter here and read; .... read = false; } } public syncrhonized void write(){ if(!read){ write
readWriteLock
类,而不使用API提供的readWriteLock
我有这样的情况:
public void read(){
if(!write){
read = true;
//any thread can enter here and read;
....
read = false;
}
}
public syncrhonized void write(){
if(!read){
write = true;
//only one thread at time can write.
....
write = false;
}
}
此代码可能会出现很多不好的情况,例如:
- 如果一个线程进入
内部,它会立即变为true,因此无法写入if(!read){…}
- 如果线程进入
内部,这将立即变为真,因此它们无法读取if(!write){…}
atomicBoolean
,但是对于同时想要读取的所有线程来说,这是一个mutex-exclusion
,这并不能解决歧义
有人能给我解释一下吗
提前谢谢。你想做的不是一个好主意。正如你已经提到的那样,已经有了一个现有的机制。为什么要重新发明轮子 如果您确实需要自己的实现,那么要正确地实现它,需要更多的同步块。您需要同步获取和释放读锁,您不能只同步对写方法的访问 我没有检查过的示例,但看起来不错。Jakob Jenkov()
典型的死锁情况。为了防止出现这种情况,请查看信号量。java.util.concurrent.locks.ReentrantReadWriteLock有什么问题
public class ReadWriteLock{
private int readers = 0;
private int writers = 0;
private int writeRequests = 0;
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();
}
}