- 在缓冲区为空时,消费者不能再进行消费
- 在缓冲区为满时,生产者不能再进行生产
- 在一个线程进行生产或消费时,其余线程不能再进行生产或消费等操作,即保持线程间的同步
- 注意条件变量与互斥锁的顺序
买家和卖家 生产者消费者
消费者去买 有商品的话 直接买 没有的话就需要等待wait
生产者生产完以后 唤醒等待中的消费者取商品 然后等待wait
package com.work.week01;
class Goods{ //消费者和生产者共同拥有的==>商品
private String name;//商品名字
private double price;//商品的价格
private boolean isProduct;//商品是否需要生产
//ture 需要生产 , false 不需要生产
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 Customer implements Runnable{ //消费者线程
private Goods goods;
public Customer(Goods goods) {
this.goods = goods;
}
public void run() {
while (true){
synchronized (goods){
if (!goods.isProduct()){
System.out.println("消费者购买了" + goods.getName() +
"价格为:" + goods.getPrice());
goods.setProduct(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;
}
public void run() {
int count = 0;
while (true){
synchronized (goods){
if (goods.isProduct()){
if (count %2 == 0) {
goods.setName("幻影");
goods.setPrice(9.9);
// System.out.println();
}else{
goods.setName("粪叉");
goods.setPrice(10.0);
}
goods.setProduct(false);
System.out.println("生产者生产了:" + goods.getName()
+ "价格为:" + goods.getPrice());
count++;
goods.notify();
} else {
try {
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Demo04 {
public static void main(String[] args) {
Goods goods = new Goods("玛莎拉蒂" , 9.9 ,
false);
Customer customer = new Customer(goods);
Productor productor = new Productor(goods);
new Thread(customer).start();
new Thread(productor).start();
}
}