生产者消费者模型+仓储模型及Java自带的线程池
一、生产者消费者模型
1.注意:一个生产者一个消费者
2.最终目的:生产一个、消费一个
3.分析:
1.产品类 – Phone
2.生产者线程 – Producer
3.消费者线程 – Consumer
4.步骤:
步骤1:生产者线程和消费者线程操作同一个资源
步骤2:在两个产品之间切换(目的:将步骤1的问题扩大化)
步骤3:如何生产一个消费一个?
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();
}
}
//消费者线程
public class Consumer extends Thread{
private Phone phone;
public Consumer(Phone phone) {
this.phone = phone;
}
@Override
public void run() {
while (true) {
synchronized (phone) {
if (!phone.isStore()) {
//没有库存
try{
//等待
phone.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println(phone.getBrand() + " -- " + phone.getPrice());
phone.setStore(false);
//唤醒
phone.notify();
}
}
}
}
public class Phone {
private String brand;
private double price;
private boolean isStore;
public Phone() {
}
public Phone(String brand, double price) {
this.brand = brand;
this.price = price;
}
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;
}
public boolean isStore() {
return isStore;
}
public void setStore(boolean isStore) {
this.isStore = isStore;
}
@Override
public String toString() {
return "Phone [brand=" + brand + ", price=" + price + "]";
}
}
//生产者线程
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{
//等待(1.当前线程进入到阻塞状态 2.将当前线程记录在对象监视器中 3.释放锁资源)
phone.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
if (flag) {
phone.setBrand("华为");
phone.setPrice(3999);
} else {
phone.setBrand("小米");
phone.setPrice(1999);
}
phone.setStore(true);
flag = !flag;
//唤醒(对象监视器中可能记录了很多等待的线程,这里唤醒的是随机一个线程)
phone.notify