生产者与消费者
生产者与消费者模型
1.一个生产者一个消费者
步骤:
1.让生产者线程和消费者线程 共同操作同一个手机对象(资源)
2.让两个产品来回切换(目的是放大第一个步骤的问题)加锁,防止脏数据的出现
3.生产一个消费一个
代码实现:
package com.dream.producer_consumer01_type01;
public class Test01 {
public static void main(String[] args) {
Phone phone = new Phone();
Producer p = new Producer(phone);
Consumer c = new Consumer(phone);
p.start();
c.start();
}
}
package com.dream.producer_consumer01_type01;
public class Phone {
private String brand;
private double price;
private boolean isStore;
public boolean isStore() {
return isStore;
}
public void setStore(boolean isStore) {
this.isStore = isStore;
}
public Phone() {
}
public Phone(String brand, double price, boolean isStore) {
super();
this.brand = brand;
this.price = price;
this.isStore = isStore;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Phone [brand=" + brand + ", price=" + price + ", isStore=" + isStore + "]";
}
}
package com.dream.producer_consumer01_type01;
//生产者线程
public class Producer extends Thread{
private Phone phone;
public Producer(Phone phone) {
this.phone = phone;
}
@Override
public void run() {
boolean flag = true;
while(true){
synchronized(phone){
if(phone.isStore()){
//有库存
try {
phone.wait();//wait:使当前线程等待,并把等待的线程记录在对象监视器(phone)中
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(flag){
phone.setBrand("华为");
phone.setPrice(3999);
}else{
phone.setBrand("小米");
phone.setPrice(1999);
}
flag = !flag;
phone.setStore(true);//设置为有库存
phone.notify();//唤醒:唤醒对象监视器中第一个等待的线程
}
}
}
}
package com.dream.producer_consumer01_type01;
//消费者线程
public class Consumer extends Thread{
private Phone phone;
public Consumer(Phone phone) {
this.phone = phone;
}
@Override
public void run() {
while(true){