package com.baosight;
public class TestPc {
public static void main(String[] args) {
Containor containor=new Containor();
Pro pro=new Pro(containor);
Bus bus=new Bus(containor);
bus.start();
pro.start();
}
}
class Pro extends Thread{
Containor containor;
public Pro(Containor containor){
this.containor=containor;
}
@Override
public void run() {
for(int i=1;i<=100;i++){
containor.push(new Chicken(i+""));
System.out.println("生产第"+i+"只鸡");
}
}
}
class Bus extends Thread{
Containor containor;
public Bus(Containor containor){
this.containor=containor;
}
@Override
public void run() {
for(int i=1;i<=100;i++){
System.out.println("消费第"+containor.pop().getName()+"只鸡");
}
}
}
class Chicken{
private String name;
public String getName() {
return name;
}
public Chicken(String name) {
this.name = name;
}
}
class Containor{
Chicken[] chickens=new Chicken[10];
int count=0;
//生产鸡
public synchronized void push(Chicken chicken){
if(count== chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chickens[count]=chicken;
count++;
this.notifyAll();
}
public synchronized Chicken pop(){
if(count== 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
//通知消费者消费
this.notifyAll();
return chickens[count];
}
}
09-02