// 测试生产者消费者模型
// 生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Producer(synContainer).start();
new Customer(synContainer).start();
}
}
// 生产者
class Producer extends Thread{
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
// 生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了"+i+"只鸡");
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 消费者
class Customer extends Thread{
SynContainer container;
public Customer(SynContainer container) {
this.container = container;
}
// 消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
System.out.println("消费了"+container.pop().id+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
// 缓冲区
class SynContainer{
// 需要一个容器
Chicken[] chickens = new Chicken[10];
// 容器计数器
int count = 0;
// 生产者生产
public synchronized void push(Chicken chicken) throws InterruptedException {
// 如果缓冲区满了,则不可以存放
if (count==chickens.length){
this.wait();
}
// 如果缓冲区没满,则可以放入产品
chickens[count] = chicken;
count++;
// 可以通知消费者了
this.notifyAll();
}
// 消费者消费
public synchronized Chicken pop() throws InterruptedException {
// 如果缓冲区为空
if (count == 0){
this.wait();
}
// 如果缓冲区有产品则可以取出产品
count--;
Chicken chicken = chickens[count];
// 吃完了,通知生产
this.notifyAll();
return chicken;
}
}
07-22
1324
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-23
705
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)