上午学了锁,敲了代码,可是怎么调试都报错java.lang.IllegalMonitorStateExceptionimport java.lang.Thread;
class Res{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
synchronized (r){
if(r.flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(x == 0){
r.name = "nike";
r.sex = "man";
}else{
r.name = "apple";
r.sex = "girl";
}
x = (x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
synchronized (r){
if(!r.flag){
try {
r.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(r.name+"..."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
class InputOutputDemo{
public static void main(String[] args){
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
也不知道错在哪里,检查不出来,麻烦解决下
|
|