卖家买车案例
汽车生产商(卖家)
收到买家的购车需求,如果有车直接购买,如果没有车,让买家等待(wait)等待生产出来之后,通知买家(唤醒notify)买家去提车
购车用户(买家)
向卖家提出购车需求,如果有车直接买,如果没车,进入等待状态(wait)
class Goods{ //商品类 可以看做生产者和消费者交流的通道
private String name; //商品名字
private double price; // 商品价格
private boolean isProduct; //是否需要生产
public Goods(String name, double price, boolean isProduct) {
this.name = name;
this.price = price;
this.isProduct = isProduct;
}
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 isProduct() {
return isProduct;
}
public void setProduct(boolean product) {
isProduct = product;
}
}
class Cusyomer implements Runnable{ //消费者线程
Goods goods;
public Cusyomer(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
while (true){ //ture 让消费者一直消费
synchronized (goods){ //锁定商品
if (!goods.isProduct()){ //判断商品是否有库存,是否需要生产 true无库存需要生产 fales有库存不需要生产
System.out.println("消费者买到了一辆"+goods.getName()+"价格为:"+goods.getPrice());
//买车
goods.setProduct(true);
//修改库存
}else { //无库存状态
try {
goods.wait(); //没库存需要等
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Prodector implements Runnable{ //生产者线程
Goods goods;
public Prodector(Goods goods) { //有参构造 获取商品的当前的属性
this.goods = goods;
}
@Override
public void run() {
int count =0; //计数器,为下面的生产何种车做准备
while (true){ //让生产者一直生产
try {
Thread.sleep(2000); //让生产者睡觉,保证消费者线程先走
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (goods){ //锁定商品
if (goods.isProduct()) { //判断库存状态 true需要生产 fales不需要生产
if (count%2==0){ //偶数生产呜呜车
goods.setName("呜呜车"); //修改商品属性-名字
goods.setPrice(998); //修改商品属性-价格
}else {
goods.setName("滴滴车"); //修改商品属性-名字
goods.setPrice(688); //修改商品属性-价格
}
goods.setProduct(false); //生产好修改商品库存
System.out.println("汽车商生产了:"+goods.getName()+"价格为"+goods.getPrice());
count++; //计数器
goods.notify(); //通知消费者来购买
}else { //有库存状态,通知消费者去购买
try {
goods.wait(); //生产商有库存,陷入等待状态,等消费者购买
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Demo1 {
public static void main(String[] args) {
Goods goods = new Goods("小汽车",5.5,false); //实例化商品
new Thread(new Cusyomer(goods)).start(); //实例化消费者线程并启动
new Thread(new Prodector(goods)).start(); //实例化生产者线程并启动
}
}