我为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();
}
}
答案 0 :(得分:1)
您的版本有利于读者(并且可能会使作家们挨饿)。 这是一个有利于作家的修改版本(并且可能使读者饿死):
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();
}
}
答案 1 :(得分:0)
要控制锁的分布方式,您需要维护一个等待线程的队列。除非您保护的代码部分很昂贵,否则简单的锁定可能会更好。