管程法
并发协作模型“生产者/消费者模式”---->管程法
- 生产者:负责生产数据的模块(可能是方法,对象,线程,进程);
- 消费者:负责处理数据的模块(可能是方法,对象,线程,进程);
- 缓冲区:消费者不能直接使用生产者的数据,他们之间有“缓冲区”.
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据两个线程共用一个缓冲区对象.
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];
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--;
this.notifyAll();
return chiken;
}
}
运行结果:
|