您的位置:首页 > 编程语言

多线程生产者与消费者问题代码模型

2017-10-19 16:02 344 查看
package li.com.thread02;

//生产者与消费者 问题的引出
class Info{
private String title;
private String content;
private boolean flag=true;  //flag =true表示可以生产 不允许消费取出   flag=false表示可以取出 不可以生产

//设置数据 (生产者)
public synchronized void set(String title,String content) {  //synchronized 解决数据错位问题  保证title 和content同事完成
if(this.flag==false){  //如果重复进入到set()方法 发现不能生产所以到等待。
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

this.title = title;
try {
Thread.sleep(100);   //休眠
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.content=content;

//生产完毕修改生产标记
this.flag=false;
//换新等待线程、
super.notify();

}
public synchronized void get() {  //保证数据同步取出

if(this.flag){  //表示还没有生产  无法取出  所以要等待
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.title+"---------"+this.content);

//修改生产标记
this.flag=true;
//换醒等待线程
super.notify();
}

}

class Producer implements Runnable{

private Info info;

public Producer(Info info){
this.info=info;
}

@Override
public void run() {

for (int i = 0; i <200; i++) {

if(i%2==0){

this.info.set("李成双","是个好学生");

}else{
this.info.set("王大崔","好农民");
}

System.out.println("生产。。。。。。"+i);

}

}

}

//消费
class Consumption implements Runnable{
private Info info;

public Consumption(Info info){
this.info=info;
}

@Override
public void run() {

for(int i=0;i<200;i++){

this.info.get();
}

}

}

public class ProCon {

public static void main(String[] args) {

Info info=new Info();
new Thread(new Producer(info)).start();
new Thread(new Consumption(info)).start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: