在我们生活中有很多这样的场景,比如食堂,我们学生负责干饭,属于消费者,工作人员负责做饭,是生产者,,而饭呢呢个,他同时被消费者和生产者同时接触,就属于临界资源。
生产者: 作用是生产产品,
生产逻辑: 通过一个生产标记,判断是否需要生产产品,如果需要生产,则生产产品,并通知消费者使用,如果不需要生产,则等待
消费者: 作用是消费产品,
消费逻辑: 判断是否有足够的产品可以消费,如果可以,则获取产品,进行消费,如果不可以,则等待
生产者代码
/**
* 生产者和消费者模式
*生产者
*/
public class Dome1 extends Thread{
private ProductPool pool;
public Dome1 (ProductPool pool){
this.pool=pool;
}
@Override
public void run() {
while (true){
String name=(int)(Math.random()*100)+"号产品";
System.out.println("生产了一件产品");
Product product=new Product(name);
try {
this.pool.push(product);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者代码
/**
* 消费者
*/
public class Dome2 extends Thread {
private ProductPool pool;
public Dome2 (ProductPool pool){
this.pool=pool;
}
@Override
public void run(){
while (true){
Product product= null;
try {
product = this.pool.pop();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费了一件产品"+product.getName());
}
}
}
产品类
/**
* 产品类
*/
public class Product {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Product(String name){
this.name=name;
}
}
产品池代码
/**
* 产品池
*/
public class ProductPool {
//存储所有产品的集合,生产者生产产品,消费者消费产品
private List<Product> products;
//产品池中产品最大数量
public int maxSize=0;
public ProductPool(int maxSize){
this.maxSize=maxSize;
//实例化产品池
this.products=new LinkedList<Product>();
}
/**
* 生产则存放商品方法
* @param product
*/
public synchronized void push(Product product) throws InterruptedException {
this.products.add(product);
//通知有产品可以消费了
this.notifyAll();
//判断是否还需要生产,
if(this.products.size()==maxSize){
this.wait();
}
}
/**
* 消费者消费方法和逻辑
* @return
* @throws InterruptedException
*/
public synchronized Product pop() throws InterruptedException {
//判断是否还有商品
if(this.products.size()==0){
this.wait();
}
//从商品池中,取出
Product product=this.products.remove(0);
//通知其他人,我已经取出了
this.notifyAll();
return product;
}
}
主函数启动
public class Program {
public static void main(String[] args) {
//产品池
ProductPool poll=new ProductPool(15);
new Dome1(poll).start();
new Dome2(poll).start();
}
}