在实现线程间通信时抱错java.lang.IllegalMonitorStateException
有两个线程类GetThread和SetThread代码如下:
package cn.itcast_01_Tread_Ticket_2_tongxing;
public class SetThread implements Runnable {
Student s;
int x = 0;
SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.lock.lock();
if (s.flag) {
try {
s.lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (x % 2 == 0) {
s.name = "张三";
s.age = 23;
} else {
s.name = "李四";
s.age = 26;
}
x++;
s.flag = true;
s.lock.notify(); //33行
s.lock.unlock();
}
}
}
package cn.itcast_01_Tread_Ticket_2_tongxing;
public class GetThread implements Runnable {
Student s;
GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.lock.lock();
if (!s.flag) {
try {
s.lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(s.name + "----" + s.age);
s.flag = false;
s.lock.notify();
s.lock.unlock();
}
}
}
报错
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at cn.itcast_01_Tread_Ticket_2_tongxing.SetThread.run(SetThread.java:33)
at java.lang.Thread.run(Thread.java:745)
|
|