欢迎来到天天文库
浏览记录
ID:39551591
大小:33.00 KB
页数:4页
时间:2019-07-06
《Java模拟生产者消费者问题》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、利用多线程模拟“生产者——消费者”问题。在“生产者——消费者”模型中,生产者Producer负责生产数据,而消费者Consumer负责使用数据。多个生产者线程会在同一时间运行,生产数据,并放到内存中一个共享的区域。期间,多个消费者线程读取内存共享区,消费里面的数据。BufferShare类packageimut.cstd.PC;publicclassBufferShared{privatestaticintMAXSIZE=100;privateinti=0;privatefloatbuf[]=newfloat[MAXSIZE
2、];publicsynchronizedvoidSend(floatdata){while(i<=buf.length){try{wait();}catch(Exceptione){System.out.println(e.getMessage());}notify();buf[i]=data;i++;}}publicsynchronizedfloatReceive(){while(i>=0){try{wait();}catch(Exceptione){System.out.println(e.getMessage());}
3、}notify();i--;returnbuf[i];}}Customer类packageimut.cstd.PC;publicclassCustomerimplementsRunnable{privateintnum;privateBufferSharedbuffer;publicCustomer(){}publicCustomer(intnum){this.num=num;}publicvoidrun(){floatdata;for(inti=0;i<3;i++){data=(float)Math.random();bu
4、ffer.Receive();System.out.println("producer"+num+":"+data);try{Thread.sleep(1000);}catch(Exceptione){System.out.println(e.getMessage());}}}}Producer类packageimut.cstd.PC;publicclassProducerimplementsRunnable{privateintnum;privateBufferSharedbuffer;publicProducer(){}
5、;publicProducer(intnum){this.num=num;}@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubfloatdata;for(inti=0;i<3;i++){data=(float)Math.random();buffer.Send(data);System.out.println("producer"+num+":"+data);try{Thread.sleep(1000);}catch(Exceptione){System.out.p
6、rintln(e.getMessage());}}}}Main函数packageimut.cstd.PC;publicclassTest{/***@paramargs*/publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubProducerpro1=newProducer(1);ThreadthreadP1=newThread(pro1);ThreadthreadP2=newThread(pro1);ThreadthreadP3=newThread(
7、pro1);Customercus1=newCustomer(1);ThreadthreadR1=newThread(cus1);ThreadthreadR2=newThread(cus1);ThreadthreadR3=newThread(cus1);threadP1.start();threadP2.start();threadP3.start();threadR1.start();threadR2.start();threadR3.start();}}
此文档下载收益归作者所有