只能从empty状态进入writing状态,一旦进入writing状态后,其它线程都不能写操作,任何写或读请求都必须等到这个线程完成写操作为止,而且waiting状态中的进程也必须一直等到写操作结束。完成操作后,返回到empty状态,发送一个通知信号,等待的线程将得到服务。
下面实现了这个信号标志
class Semaphore{
final static int EMPTY=0;
final static int READING=1;
final static int WRITING=2;
protected int state=EMPTY;
protected int readCnt=0;
public synchronized void readLock(){
if(state==EMPTY){
state=READING;
}
else if(state==READING){
}
else if(state==WRITING){
while(state==WRITING){
try {wait();}
catch(InterruptedException e){;}
}
state=READING;
}
readCnt++;
return;
}
public synchronized void writeLock(){
if(state==EMPTY){
state=WRITING;
}
else{
while(state!=EMPTY){
try {wait();}
catch(InterruptedException e) {;}
}
}

