[求解答]java.lang.IllegalMonitorStateException
请问,如下的报错问题是怎么回事? 我不想把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 易做图;
private int count = 1;
boolean flag = false;
int x = 0;
public void set(String name, String 易做图) {
this.name = name;
this.易做图 = 易做图;
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 + "...." + 易做图 + 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 + "...." + 易做图 + 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();
}
}
--------------------编程问答-------------------- 原来wait(),notify()忘记加锁了 --------------------编程问答-------------------- 很多错误都很奇怪,结果最后努力探索,发现自己小小的笔误。
伤心 --------------------编程问答-------------------- 发现wait(),notify()加锁了后还是不同步。
补充:Java , Java SE