请问,如下的报错问题是怎么回事? 我不想把product类中切换写在factory中,该如何解决呢?谢谢大家帮忙指点迷津错误提示:Thread-1produce....mike....man2
Thread-0消费....mike....man2
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at Treadpakg.product.run(exInOutDemo.java:69)
at java.lang.Thread.run(Unknown Source)
package Treadpakg;class factory {
private String name;
private String sex;
private int count = 1;
boolean flag = false;
int x = 0; public void set(String name, String sex) {
this.name = name;
this.sex = sex;
count++;
} public void pro() {
// while (flag) {
// try {
// wait();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// if (x%2==0) {
// set("mike", "man");
// }else {
// set("哈哈", "女女女女");
// }
// x=(x+1)%2; System.out.println(Thread.currentThread().getName() + "produce"
+ "...." + this.name + "...." + sex + count);
flag = true;
notifyAll();
} public void output() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "消费" + "...."
+ this.name + "...." + sex + count);
flag = false;
notifyAll();
}}class product implements Runnable {
private factory fa; public product(factory fa) {
super();
this.fa = fa;
} public void run() {
int x = 0;
while (true) {
synchronized (fa) {
while (fa.flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (x % 2 == 0) {
fa.set("mike", "man");
} else {
fa.set("哈哈", "女女女女");
}
x = (x + 1) % 2;
fa.pro();

}
}
}
}class shop implements Runnable {
private factory fa; public shop(factory fa) {
super();
this.fa = fa;
} public void run() { while (true) {
synchronized (fa) {
fa.output();

}
}
}
}public class exInOutDemo {
public static void main(String[] args) {
factory f = new factory();
new Thread(new shop(f)).start();
new Thread(new product(f)).start();
new Thread(new shop(f)).start();
new Thread(new product(f)).start();
new Thread(new shop(f)).start();
new Thread(new product(f)).start();
}
}