欢迎来到天天文库
浏览记录
ID:39474253
大小:51.00 KB
页数:4页
时间:2019-07-04
《基于Java的生产者消费者线程安全问题的详细代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、包为com.appPublicResource为功能资源类看类名可以理解!packagecom.app;publicclassPublicResource{privateintnumber=0;/**增加*/publicsynchronizedintincrease(){while(number==20){try{System.out.println("警告!仓库满了……");this.wait();}catch(Exceptione){e.printStackTrace();}}number++;this.notify();returnnumber;}/**减少*/publicsynchr
2、onizedintdecrease(){while(number==0){try{System.out.println("警告!仓库空了……");this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}number--;this.notify();returnnumber;}}生产者类packagecom.app;publicclassProducerimplementsRunnable{publicPublicResourcepublicResource;publicProducer(PublicResourcers)
3、{this.publicResource=rs;}publicvoidrun(){while(true){try{Thread.sleep((long)(Math.random()*200));}catch(InterruptedExceptione){e.printStackTrace();}intnumber=this.publicResource.increase();System.out.println(Thread.currentThread().getName()+"生产一个剩余数量为:"+number);}}}消费者类packagecom.app;publicclassCons
4、umerimplementsRunnable{publicPublicResourcepublicResource;publicConsumer(PublicResourcers){this.publicResource=rs;}publicvoidrun(){while(true){try{Thread.sleep((long)(Math.random()*200));}catch(InterruptedExceptione){e.printStackTrace();}intnumber=this.publicResource.decrease();System.out.println(T
5、hread.currentThread().getName()+"消费一个剩余数量为:"+number);}}}主类测试用packagecom.app;publicclassTest{publicstaticvoidmain(String[]args){PublicResourcepr=newPublicResource();Producerpro1=newProducer(pr);Threadth1=newThread(pro1);th1.setName("生产者1号");th1.start();Producerpro2=newProducer(pr);Threadth2=newThrea
6、d(pro2);th2.setName("生产者2号");th2.start();Producerpro3=newProducer(pr);Threadth3=newThread(pro3);th3.setName("生产者3号");th3.start();Consumercon1=newConsumer(pr);Threadth4=newThread(con1);th4.setName("消费者1号");th4.start();Consumercon2=newConsumer(pr);Threadth5=newThread(con2);th5.setName("消费者2号");th5.st
7、art();Consumercon3=newConsumer(pr);Threadth6=newThread(con3);th6.setName("消费者3号");th6.start();}}运行结果图如下:因为线程休眠时间问题很少出现仓库满了,增加生产者线程或者增长消费者消费时间可以出现仓库爆满的现象。临界资源是20。
此文档下载收益归作者所有