求大神答疑解惑,这是简单的生产者消费者模型,在多了一个生产者,或者多了一个消费者的时候,数据会产生错误;比如多了一个消费者的时候,会有负数产品产生,求大神答疑解惑,如何改进,可以有多个生产者对多个消费者,保证数据正确性;
下面贴代码:
//产品数据
package Thread_p_c;
public class Product {
private int pno=0;
public Product(String pname) {
this.pname=pname;
}
private String pname ="灯泡";
private boolean flag = true;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getPno() {
return pno;
}
public void setPno(int pno) {
this.pno = pno;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
// 测试类
package Thread_p_c;
public class pc_model {
private int i = 0;
private boolean flag = true;
public static void main(String[] args) {
Product p = new Product("灯泡");
Thread t1 = new Thread(new Producer(p));
Thread t2 = new Thread(new Consumer(p));
t1.start();
t2.start();
// new Thread(new Producer(p)).start();
// new Thread(new Consumer(p)).start();
}
}
//生产者
package Thread_p_c;
public class Producer implements Runnable {
private Product p;
public Producer (Product p) {
this.p = p;
}
@Override
public void run() {
while(true) {
synchronized (p) {
if(!p.isFlag()) {
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("生产者开始制造产品:");
int i = p.getPno();
i++;
p.setPno(i);
p.setFlag(false);
System.out.println("生产者生产了" + p.getPname() + "->" + p.getPno());
System.out.println("生产者结束生产,等待消费!");
p.notify();
}
}
}
}
//消费者
package Thread_p_c;
public class Consumer implements Runnable {
private Product p;
public Consumer(Product p) {
this.p=p;
}
@Override
public void run() {
while(true) {
synchronized (p) {
if (p.isFlag() || p.getPno()<=0) {
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费者进入商场消费");
System.out.println("消费者开始消费产品:");
System.out.println("消费者消费中.......");
int i = p.getPno();
System.out.println("消费者结束消费,消费了" + p.getPname() + ":" + p.getPno());
i--;
p.setPno(i);
p.setFlag(true);
p.notify();
System.out.println("消费结束,正在通知生产厂家生产...");
}
}
}
}