package com.qf.a.CustomProduct;
class Goods {
private String name;//名字属性
private double price;//价格属性
private boolean isProducted;//是否生产的boolean类型
public Goods(String name, double price, boolean isProducted) {
this.name = name;
this.price = price;
this.isProducted = isProducted;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isProducted() {
return isProducted;
}
public void setProducted(boolean producted) {
isProducted = producted;
}
}
class Customers implements Runnable {
private Goods goods;//创建同一个物品,类当成属性
public Customers(Goods goods) {//无参构造
this.goods = goods;
}
@Override
public void run() {
while (true) {//格式
synchronized (goods) {//synchronized,锁资源物品
if (!goods.isProducted()) {//如果物品不生产,直接买
System.out.println("小白可直接购买" + goods.getName() + ",价格为" + goods.getPrice());
//购买完了,商品没了,商品标记为true;用set来设置
goods.setProducted(true);
//唤醒生产者让其生产
goods.notify();
} else {
//需要生产 让消费者等待
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Productor implements Runnable {
private Goods goods;
public Productor(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
int count = 0;//计数器,生产用的
while (true) {
try {
Thread.sleep(1000);//让生产者睡1S
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (goods) {
if (goods.isProducted()) {//物品生产
if (count % 2 == 0) {
//偶数就生产茅台
goods.setName("茅台");
goods.setPrice(1499.9);
} else {
//奇数就生产江小白
goods.setName("江小白");
goods.setPrice(9.9);
}
goods.setProducted(false);//生产完毕
System.out.println("生产者生产了:" + goods.getName() + ",价格为:" + goods.getPrice());//生产的东西输出一下
count++;//计数器再次循环
goods.notify();//唤醒消费者
} else {//就是有商品,商品等待消费者唤醒
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Deom1 {
public static void main(String[] args) {
Goods goods = new Goods("江小白", 9.9, true);//创建对象
Customers customer = new Customers(goods);//创建顾客
Productor productor = new Productor(goods);//
new Thread(customer).start();
new Thread(productor).start();
}
}