我针对Java中的读写器问题开发了解决方案(有关此http://lass.cs.umass.edu/~shenoy/courses/fall08/lectures/Lec11.pdf的一些信息)。
但是,我不确定如何修改代码以偏爱作者或为读者和作者赋予相同的优先级。我的代码是什么类型的问题,我怎么看?
public class ReaderWriter{
int numberOfReaders;
int numberOfWriters;
public ReaderWriter(){
this.numberOfReaders = 0;
this.numberOfWriters = 0;
}
public synchronized void requestRead(){
while(this.numberOfWriters > 0)
wait();
this.numberOfReaders++;
}
public synchronized void releaseRead(){
this.numberOfReaders--;
notifyAll();
}
public synchronized void requestWrite(){
while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
wait();
this.numberOfWriters++;
}
public synchronized void releaseWrite(){
this.numberOfWriters--;
notifyAll();
}
}
最佳答案
您的版本偏爱读者(并且可能饿死作家)。
这是一个偏爱作者的修改版本(可能会使读者感到饥饿):
int numberOfReaders;
int numberOfWriters;
int numberOfRequestedWriters; // ++
public ReaderWriter(){
this.numberOfReaders = 0;
this.numberOfWriters = 0;
this.numberOfRequestedWriters = 0; // ++
}
public synchronized void requestRead(){
while(this.numberOfWriters > 0 // --
|| this.numberOfRequestedWriters > 0) // ++
wait();
this.numberOfReaders++;
}
public synchronized void releaseRead(){
this.numberOfReaders--;
notifyAll();
}
public synchronized void requestWrite(){
this.numberOfRequestedWriters++; // ++
while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
wait();
this.numberOfRequestedWriters--; // ++
this.numberOfWriters++;
}
public synchronized void releaseWrite(){
this.numberOfWriters--;
notifyAll();
}
}