线程的生产者和消费者管程法的代码
/*
* 使用管程法实现生产者消费者模式
*/
public class CoTest01 {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//多线程的生产者
class Productor extends Thread {
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
@Override
public void run() {
// 生产
for (int i = 1; i < 100; i++) {
System.out.println("生产第 -->"+i+"个馒头");
container.push(new Steamedbun(i)); //new了馒头的对象
}
}
}
//多线程的消费者
class Consumer extends Thread {
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
// 消费
for (int i = 0; i < 1000; i++) {
System.out.println("消费第-->"+container.pop().id+"个馒头");
}
}
}
//缓冲区
class SynContainer {
// 存储数据的容器
Steamedbun[] buns = new Steamedbun[10];
int count = 0;// 计数器
// 储存-->生产者做的事情
public synchronized void push(Steamedbun bun) {
//何时能生产 容器存在空间
//不能生产 只有等待
if(count==buns.length) {
try {
this.wait(); //线程阻塞,消费者通知生产解除
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//存在空间可以生产
buns[count] = bun;
count++;
//存在数据了,可以通知消费了
this.notifyAll();
}
// 获取-->消费者做的事情
public synchronized Steamedbun pop() {
//何时消费 看容器中是否存在数据
//没有数据只有等待
if(count==0) {
try {
this.wait();//线程阻塞 生产者通知消费解除阻塞
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//存在数据可以消费
count--;
Steamedbun bun = buns[count];
this.notifyAll();//消费了有空间了就可以通知你生产了
return bun;
}
}
//馒头
class Steamedbun {
int id;
public Steamedbun(int id) {
this.id = id;
}
}