一旦牵涉到生产者(卖家)消费者(买家)
有一个生产者,一个消费者,生产者没有商品的时候进入生产时间,消费者需要等待。如果不需要生产,那么消费者可以直接购买。二对于消费者来说,在商品不需要生产的时候,可以直接买。在商品需要生产的时候,则需要等待。而生产者、消费者两者之间的纽带则是商品(商品是否已经生产)。
package com.test.week.six.monday;
class Goods{//商品类
private String name;//商品名称
private double price;//商品价格
private boolean isshengchan;//是否再生产
public Goods(String name, double price, boolean isshengchan) {
this.name = name;
this.price = price;
this.isshengchan = isshengchan;
}
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 isIsshengchan() {
return isshengchan;
}
public void setIsshengchan(boolean isshengchan) {
this.isshengchan = isshengchan;
}
}
class Client implements Runnable{//消费者线程
private Goods goods;
public Client(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
while (true){
synchronized (goods){
if (!goods.isIsshengchan()){
//直接购买
System.out.println("消费者消费:"+goods.getName()+" 消费金额"+goods.getPrice()+"元");
//买完以后 再生产需求改写为true
goods.setIsshengchan(true);
// 唤醒厂家干活
goods.notify();
}else {
// 不买 消费者等待
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Vender implements Runnable{//厂家线程
private Goods goods;
public Vender(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
// 创建变量表示奇偶
int count = 0;
while (true){
// 生产者睡眠等待消费者消费
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (goods){
// 判断是否需要再生产
if (goods.isIsshengchan()){
// 判断奇偶,生产不同商品
if (count % 2 == 0){
goods.setName("泡面");
goods.setPrice(4.5);
}else {
goods.setName("香肠");
goods.setPrice(3);
}
count++;
// 生产完成,唤醒消费者消费
goods.notify();
System.out.println("厂家生产了:"+goods.getName()+" 售价为:"+goods.getPrice()+"元");
goods.setIsshengchan(false);
}else {
//不需要生产,线程等待
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Demo1 {
public static void main(String[] args) {
Goods goods = new Goods("大鸡腿", 6, false);
Client client = new Client(goods);
Vender vender = new Vender(goods);
new Thread(client).start();
new Thread(vender).start();
}
}