package com.syn;
public class TestPc {
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 = 0; i < 100; i++) {
container.push(new RostChichen(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 RostChichen{
int id;
public RostChichen(int id){
this.id=id;
}
}
//同步缓冲区
class SynContainer{
//建立一个数组,设定容器大小
RostChichen[] rostChichens= new RostChichen[10];
//容器计数器
int count=0;
//生产者放入产品
public synchronized void push (RostChichen chichen){
//如果容器满了,就要等待消费
if (count == rostChichens.length){
//通知消费者等待生产
try{
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
rostChichens[count]=chichen;
count++;
//可以通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized RostChichen pop(){
//如果容器空了,就要等待生产
if (count == 0){
//等待生产者生产
try{
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
count--;
RostChichen chichen = rostChichens[count];
//吃完通知生产者
this.notify();
return chichen;
}
}