package com.li;
//测试:生产者消费者问题-->利用缓冲区解决:管程法
//生产者、消费者、产品、缓冲区
public class TestPC {
public static void main(String[] args) {
Buffer buffer = new Buffer();
Producers product = new Producers(buffer);
Consumer consumer = new Consumer(buffer);
product.start();
consumer.start();
}
}
//生产者
class Producers extends Thread{
Buffer buffer;
public Producers (Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
buffer.push(new Product(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产者生产了" + i + "个产品");
}
}
}
//消费者
class Consumer extends Thread{
Buffer buffer;
public Consumer (Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
System.out.println("消费者取走了--->" + buffer.take().id + "个产品");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品
class Product {
int id;//产品编号
public Product(int id) {
this.id = id;
}
}
//缓冲区
class Buffer {
//产品类型的数组来装产品
Product[] products = new Product[10];//缓冲区容量
int count = 0;//容量中的产品计数
//生产者放入产品
public synchronized void push (Product product) throws InterruptedException {
//如果容器满了,通知消费者消费,生产者等待
if (count==products.length) {
//生产等待
this.wait();
}
//放入产品
products[count] = product;
count++;
//容量满了,通知消费者消费
this.notifyAll();
}
//消费者取走产品
public synchronized Product take() throws InterruptedException {
//如果容器没有产品,通知消费者等待,生产者生产
if (count==0) {
//通知消费者等待
this.wait();
}
//消费者取走产品
count--;
Product product = products[count];
//生产者等待
this.notifyAll();
return product;
}
}