public class TestProducerConsumer{
public static void main(String args[]){
Basket basket = new Basket(6);
Producer p1 = new Producer(basket);
Consumer c1 = new Consumer(basket);
new Thread(p1).start(); //启动生产者
try {
Thread.sleep(3000);
} catch(InterruptedException e){
e.printStackTrace();
}
new Thread(c1).start(); //启动消费者
}
}
class Mt{ //馒头类
int mid;
Mt(int mid){
this.mid = mid;
}
}
class Basket { //篮子 先进后出
public int index = 0;
public int capacity;
public Mt mtarr[];
public Basket(int capacity) {
this.capacity=capacity;
mtarr = new Mt [this.capacity];
}
}
class Producer implements Runnable { //生产者
private static int pid=0;
public Basket basektp;
输出的错误信息:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at Producer.produce(TestProducerConsumer.java:57)
at Producer.run(TestProducerConsumer.java:43)
at java.lang.Thread.run(Thread.java:662)
Exception in thread "Thread-1" java.lang.NullPointerException
at Consumer.consume(TestProducerConsumer.java:82)
at Consumer.run(TestProducerConsumer.java:70)
at java.lang.Thread.run(Thread.java:662)作者: 刘基军 时间: 2012-4-23 22:52
1.java.lang.IllegalMonitorStateException异常原因:
wait()/notify()/notifyAll(),应该是由监视器对象(锁对象)进行调用,而不能有其他对象调用
2.见代码中标注