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(flag)
try{r.wait();}catch(Exception e){}
if(x==0)
{
r.name="lili";
r.sex="girl";
}
else
{
r.name="张三";
r.sex="男";
}
x=(x+1)%2;
r.flag=true;
notify();
}
}
}
}
class output implements Runnable
{ private Res r;
output(Res r)
{
this.r=r;
}
public void run()
{while(true)
{synchronized(r)
{if (!flag)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"......"+r.sex);}
r.flag=false;
notify();
}
}
}
}//编译时提示这一行有错误,需要class,interface或enum
class waitDemo
{
public static void main(String[] args)
{ Res r=new Res();
input in=new input(r);
input out=new input(out);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
} |
|