public class Produce {
int num;
public int getNum() {
return num;
}
public void add() {
this.num++;
System.out.println("生产了一个产品");
System.out.println("还有"+this.getNum()+"个产品");
}
public void subtract() {
this.num--;
System.out.println("消耗了一个产品");
System.out.println("还有"+this.getNum()+"个产品");
}
public void setNum(int num) {
this.num = num;
}
public Produce(int num) {
super();
this.num = num;
}
}
产品类, 产品的数量在 0到10之间,但是类里没表现出来。
public class Producer implements Runnable {
Produce Produce;
public Producer(Produce produce) {
Produce = produce;
}
@Override
public void run() {
while(true){
synchronized (Produce) {
if(Produce.getNum()==0){
Produce.add();
notify();
}else if(Produce.getNum()==10){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Produce.add();
}
}
}
}
}
这个是生产者类,中间有判断产品数量的 ,等于十 等待,等于一,增加一个后,通知消费者,否则正常生产,
public class Consumer implements Runnable{
Produce Produce;
public Consumer(Produce produce) {
Produce = produce;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (Produce) {
if(Produce.getNum()==10){
Produce.subtract();
notify();
}else if (Produce.getNum()==0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Produce.subtract();
}
} } }
}
消费者类,
public static void main(String[] args) {
// TODO Auto-generated method stub
Produce produce=new Produce(8);
Consumer consumer=new Consumer(produce);
Producer Producer=new Producer(produce);
new Thread(Producer).start();
new Thread(consumer).start();
}
测试类
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at 生产者.Producer.run(Producer.java:20)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at 生产者.Consumer.run(Consumer.java:16)
at java.lang.Thread.run(Unknown Source)
最后总是这个错误,包的名字是中文,求高手帮我解答一下,哪错了,而且那
notify(); wait();方法都是在eclipse里直接用的,具体的对象都不用写,总觉得有点错误似的, |