- 1、本文档共5页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
利用多线程模拟“生产者——消费者”问题。在“生产者——消费者”模型中,生产者Producer负责生产数据,而消费者Consumer负责使用数据。多个生产者线程会在同一时间运行,生产数据,并放到内存中一个共享的区域。期间,多个消费者线程读取内存共享区,消费里面的数据。
模拟生产者-消费者问题的UNL图:
图3 生产者-消费者UML
图3为模拟生产者-消费者的UML图,Product类为生产者产生的产品类,Producer类为生产者,Consumer类为消费者,QueueMessage类用来存储多个生产者产生产品以及提供多个消费者消费产品。Test类来测试“生产者-消费者”模拟系统。
3、模拟生产者-消费者问题的程序清单
package imut.cstd.j09_2.shiyan3;
public class Product { //产品类
private String pname;
public String getPname(){
return pname;
}
public void setPname(String pname){
this.pname = pname;
}
}
package imut.cstd.j09_2.shiyan3;
import java.util.LinkedList;
public class QueueMessage { //共享区类
private static int num = 0;
private final static int MAX_num = 30;//上线商品
private LinkedListProductqueue = new LinkedListProduct();
public boolean isEmpty(){
return queue.isEmpty();
}
public synchronized Product get(){
Product temp = null;
if(queue.isEmpty()){
System.out.println(Thread.currentThread().getName()+消费者+:+目前没有可消费的商品!);
try{
this.wait();
}catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
else if(!queue.isEmpty()){
try {
num--;
temp = queue.poll();
this.wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+消费者+\t消费的商品号:+temp.getPname()+\t目前商品的数量是:+num);
}
this.notifyAll();
return temp;
}
public synchronized void add(Product temp){
if(numMAX_num){
num++;
this.queue.add(temp);
System.out.println(Thread.currentThread().getName()+生产者+\t产生的商品号:+temp.getPname()+\t目前商品的数量是:+num);
}
else if(numMAX_num){
System.out.println(生产的商品的数量已经满足:+num+生产者+Thread.currentThread().getName()+产生的商品存不了了!);
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notifyAll();
}
}
package imut.cstd.j09_2.shiyan3;
public class Producer implements Runnable{ //生产者类
private QueueMessage queue ;
public QueueMessage getQueue(){
return queue;
}
文档评论(0)