public class ProducerConsumer{
/**
* @param args
*/
class Car implements Runnable{
Belt belt=null;
boolean flag=true;
public Car(Belt belt){
this.belt=belt;
}
public void consumer(){
try{
Thread.sleep((int)(100*Math.random()));
}catch(InterruptedException e){
e.printStackTrace();
}
Stone stone=belt.deQueue();
if(stone!=null)
System.out.println(Thread.currentThread().getName()+"consumer"+stone.number+"stone");
}
public void run(){
while(flag){
consumer();
}
}
public void shutdown(){
flag=false;
}
}
class QuarryingMachine implements Runnable{
int number=0;
Belt belt=null;
String who;
boolean flag=true;
public QuarryingMachine(Belt belt){
this.belt=belt;
}
public void producer(){
try{
Thread.sleep((int)(100*Math.random()));
}catch(InterruptedException e){
e.printStackTrace();
}
belt.enQueue(new Stone(Thread.currentThread().getName(),++number));
System.out.println(Thread.currentThread().getName()+"produce"+number+" stone");
}
public void run(){
while(flag)
producer();
}
public void shutdown(){
flag=false;
}
}
class Belt{
public static final int N0=10+1;
Stone[] queue=new Stone[N0];
int front=0,rear=0;
public synchronized void enQueue(Stone stone){
while((rear+1)%N0==front)
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
queue[rear]=stone;
rear=(rear+1)%N0;
notifyAll();
}
public synchronized Stone deQueue(){
while(rear==front){
try {
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
Stone stone=queue[front];
front=(front+1)%N0;
notifyAll();
return stone;
}
}
class Stone{
String who;
int number;
public Stone(String who,int number){
this.who=who;
this.number=number;
}
}
public static void main(String[] args) {
Belt belt=new Belt();
Car car=new Car(belt);
QuarryingMachine q=new QuarryingMachine(belt);
Thread car1=new Thread(car,"zhang");
Thread car2=new Thread(car,"li");
//Thread car3=new Thread(car,"wang");
car1.start();
car2.start();
//car3.start();
Thread q1=new Thread(car,"wang");
Thread q2=new Thread(car,"werda");
Thread q3=new Thread(car,"kgjh");
q1.start();
q2.start();
q3.start();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
car.shutdown();
q.shutdown();
}
}
这是因为ProducerConsumer是一个动态的内部类,创建这样的对象必须有实例与之对应,程序是在静态方法中直接调用动态内部类会报这样错误。这样的错误好比类中的静态方法不能直接调用动态方法。可以把该内部类声明为static。或者不要在静态方法中调用。
那么为什么非静态方法不能调用动态方法呢,从面向对象的角度来说,动态方法与对象是联系密切的,比如发动是一个方法,它与汽车这个对象是关联的,所以只有new了汽车这个对象才能执行汽车.发动
比如本程序只需首先建个ProducerConsumer对象即可。
ProducerConsumer p=new ProducerConsumer();
Belt belt=p.new Belt();
Car car=p.new Car(belt);
QuarryingMachine q=p.new QuarryingMachine(belt);