class Res
{
String name;
String sex;
boolean flag=false;
}
class Input implements Runnable
{
private Res r;
//Object obj=new Object();
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r) //可以用Input.class
{
if(r.flag)
try{r.wait();}catch(Exception e){}
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女";
}
}
x=(x+1)%2;
r.flag=true;
r.notify();
}
}
}
class Output implements Runnable
{
private Res r;
//Object obj=new Object();
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(Exception e){}
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();
}
}
运行上面的代码 编译通过 运行报错
错误提示 IllegalMonitorStateException
求解 错在哪里 怎么修改 |