欢迎来到天天文库
浏览记录
ID:53564633
大小:45.00 KB
页数:7页
时间:2020-04-04
《操作系统读者写者问题算法.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、读者优先publicclassMYRW{publicstaticvoidmain(String[]args){CubbyHolec=newCubbyHole();Readerr1=newReader(1,c);Readerr2=newReader(2,c);Readerr3=newReader(3,c);Readerr4=newReader(4,c);Writerw1=newWriter(1,c);Writerw2=newWriter(2,c);r1.start();try{Thread.sleep(1000);r2.start();Thr
2、ead.sleep(1000);w1.start();Thread.sleep(1000);r3.start();Thread.sleep(1000);w2.start();Thread.sleep(1000);r4.start();Thread.sleep(1000);}catch(Exceptione){}}}classCubbyHole{intreadCount,writeCount;booleansourceReading=false,sourceWriting=false;publicCubbyHole(){readCount=0
3、;writeCount=0;sourceReading=false;sourceWriting=false;}publicsynchronizedintstartRead(){while(writeCount>0&&readCount==0){System.out.println("readeriswaiting");try{wait();}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}readCount++;if(readC
4、ount>0)sourceReading=true;returnreadCount;}publicsynchronizedintendRead(){readCount--;if(readCount==0)sourceReading=false;notifyAll();//System.out.println("onereaderfinishedreading");returnreadCount;}publicsynchronizedvoidstartWrite(){writeCount++;while(sourceReading==true
5、
6、
7、sourceWriting==true){System.out.println("Writeriswaiting");try{wait();}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}sourceWriting=true;}publicsynchronizedvoidendWrite(){writeCount--;sourceWriting=false;//System.out.println("onewriterfi
8、nishedwriting");notifyAll();}}classReaderextendsThread{CubbyHolec;intrNumber;publicReader(intr,CubbyHolec){rNumber=r;this.c=c;}publicvoidrun(){intx;if(true){//System.out.println("读线程"+rNumber+"正在休眠");try{//Thread.sleep(3000);System.out.println("读线程"+rNumber+"申请读");x=c.star
9、tRead();//Thread.sleep(3000);System.out.println("读线程"+rNumber+"正在读,共有"+c.readCount+"个线程正在读");Thread.sleep(2500);System.out.println((x=c.endRead())+"读线程"+rNumber+"已经完成读操作,h还有"+x+"个线程在读");}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}}cla
10、ssWriterextendsThread{intwNumber;CubbyHolec;publicWriter(intw,CubbyHolec){wNumber=w;this.
此文档下载收益归作者所有