生产者与消费者模型是Java多线程经典模型,它的主要意思是有一个公共的商品区,生产者项商品区生产商品,消费者从中取走商品,最理想的状态就是生产者生产一个商品消费者就从商品中取走一个商品,二者同时执行,所以采用多线程机制,随着多线程的使用就容易产生商品取出错误,商品生产重复问题,能有效解决此问题的方式就是线程的等待与唤醒加静态代码块。有必要说明一下线程的等待和唤醒都是Object类的方法。
class InFo{
//商品
private String name;
private String money;
private boolean flag=true;//布尔标记控制线程的等待与唤醒
//静态方法保证操作同一不会出现输出和赋值不同意匹配的问题
public synchronized void set(String name,String money) {
if(flag==false) {//说明不能生产
try {
super.wait();//object类中的方法让此线程进入等待状态
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
//没有等待或者等待状态结束执行赋值
this.name=name;
this.money=money;
//修改标记等待取走商品
this.flag=false;
//唤醒其他等待线程
super.notify();
}
public synchronized void get() {
if(flag==true) {//表明此刻正在生产不能取出商品
try {
//现场进入等待状态
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
System.out.println(this.name+"--"+this.money);
//标记修改等待生产商品
flag=true;
//唤醒其他等待线程也是来自object类的方法
super.notify();
}
}
class Produce implements Runnable{
protected InFo inFo;
public Produce(InFo inFo) {
// TODO Auto-generated constructor stub
this.inFo=inFo;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<100;i++) {
if(i%2==0) {
inFo.set("apple", "15");}
else{
inFo.set("banana", "25");
}
}
}
}
class Custom implements Runnable{
private InFo info;
public Custom(InFo inFo) {
this.info=inFo;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<100;i++) {
info.get();
}
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
InFo inFo=new InFo();
new Thread(new Produce(inFo)).start();;
new Thread(new Custom(inFo)).start();;
}
}