管程法
并发协作模型“生产者/消费者模式”---->管程法
- 生产者:负责生产数据的模块(可能是方法,对象,线程,进程);
- 消费者:负责处理数据的模块(可能是方法,对象,线程,进程);
- 缓冲区:消费者不能直接使用生产者的数据,他们之间有“缓冲区”.
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据两个线程共用一个缓冲区对象.
//生产者与 消费者 鸡肉:wait()以及notifyAll(),定义一个缓冲区:管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Producter(container).start();
new Customer(container).start();
}
}
class Producter extends Thread{
SynContainer container;
public Producter(SynContainer container){
this.container=container;
}
public void run(){
for (int i = 1; i <100; i++) {
try {
this.container.push(new Chiken(i)); //给每只鸡设置编号
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了第" + i+"只鸡");
}
}
}
class Customer extends Thread {
SynContainer container;
public Customer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 1; i < 100; i++) {
try {
System.out.println("消费了第" + this.container.pop().id+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品
class Chiken {
int id;
public Chiken(int id) {
this.id = id;
}
}
class SynContainer {
//定义一个缓冲区
int count = 0;
Chiken chikens[] = new Chiken[10]; //chikens数组
public synchronized void push(Chiken chiken) throws InterruptedException { //生产 者
if (count == chikens.length) {
//当缓冲区鸡的数量满了之后,生产者等待,消费者进入
this.wait();
}
chikens[count] = chiken;
count++;
//可以通知消费者消费
this.notifyAll();
}
public synchronized Chiken pop() throws InterruptedException { //消费者消费
if (count == 0) {
//提醒消费者等待,生产者进入
this.wait();
}
Chiken chiken = chikens[count-1];//这里是count-1,要避免数组越界
count--;
this.notifyAll(); //通知生产值生产
return chiken; //返回,让消费者消费
}
}
运行结果: