管程法
利用缓冲区来解决生产者消费者问题
/**
* 生产者消费者之管程法
*/
public static void main(String[] args) {
//缓冲区
SynContainer synContainer = new SynContainer();
new Producer(synContainer).start();
new Consumer(synContainer).start();
}
}
//产品
class Product {
int id;
public Product(int id) {
this.id = id;
}
}
//生产者
class Producer extends Thread {
//缓冲区对象
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//调用生产方法
container.push(new Product(i));
System.out.println("生产了" + i + "产品");
}
}
}
//消费者
class Consumer extends Thread {
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了" + container.pop().id + "产品");
}
}
}
//缓冲区
class SynContainer {
//容器
Product[] products = new Product[10];
//容器计数器
int count = 0;
//生产者生产
public synchronized void push(Product product) {
//判断是否已经达到生产满了,满了就等待,让消费者消费
if (count == products.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产并将产品放入容器
products[count] = product;
//计数
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费(需要返回消费数量)
public synchronized Product pop() {
//判断是否有产品可以消费,没有就等待,通知生产者生产
if (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始消费
count--;
//返回消费信息
Product product = products[count];
//通知生产者生产
this.notifyAll();
return product;
}