生产者生成产品,消费者消费产品 仓库满的时候,生产者停止生成,仓库空的时候,消费者停止消费
使用多线程实现
第一步,需要创建一个产品类Products.java
/**
* 生产者和消费者模式
* 产品类
*/
public class Products {
//产品名称
private String name;
public Products(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第二步,需要一个仓库
/**
* @author 79282
* 产品池
*/
public class ProductPool {
private List<Products> productsList;
private int maxSize ;
public ProductPool(int maxSize) {
this.maxSize = maxSize;
this.productsList = new LinkedList<>();
}
//生产产品
public synchronized void push(Products products) {
if (productsList.size() == maxSize) {
//产品池满了 不需要生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产
this.productsList.add(products);
System.out.println("生产了产品" + Thread.currentThread().getId());
this.notifyAll();
}
//消费产品
public synchronized Products pop() {
if (productsList.size() == 0) {
//产品池空了 停止消费
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始消费
Products products = this.productsList.remove(0);
System.out.println("消费了产品" + Thread.currentThread().getId());
this.notifyAll();
return products;
}
}
第三步,创建消费者和生产者 继承Thread类
/**
* @author 79282
* 消费者
*/
public class Consumer extends Thread {
private ProductPool productPool;
public Consumer(ProductPool productPool) {
this.productPool = productPool;
}
@Override
public void run() {
while (true) {
Products pop = this.productPool.pop();
System.out.println("消费了" + pop.getName());
}
}
}
/**
* @author 79282
* 生产者
*/
public class Productor extends Thread {
private ProductPool productPool;
public Productor(ProductPool productPool) {
this.productPool = productPool;
}
@Override
public void run() {
while (true) {
String name = (int) (Math.random() * 100) + "号产品";
System.out.println("生产了一件产品" + name);
Products products = new Products(name);
this.productPool.push(products);
}
}
}
最后创建测试类
/**
* @author 79282
*/
public class Test01 {
public static void main(String[] args) {
ProductPool productPool = new ProductPool(10);
Productor productor = new Productor(productPool);
Consumer consumer = new Consumer(productPool);
productor.start();
consumer.start();
}
}