class WaitAndNotify2
{
public static void main(String[] args)
{
Resource a=new Resource();
Input in=new Input(a);
Output ou=new Output(a);
new Thread(in).start();
new Thread(ou).start();
}
}
class Resource
{
private String name;
private String sex;
private boolean flag;
public synchronized void setResource(String name,String sex)
{
if (flag==false)
{
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
else
{
try{this.wait();}catch(Exception e){}
}
}
public synchronized void outResource()
{
if(flag==true)
{
System.out.println(name+" "+sex);
flag=false;
this.notify();
}
else
{
try{this.wait();}catch(Exception e){}
}
}
}
class Input implements Runnable
{
private Resource r;
private int x;
Input(Resource r)
{
this.r=r;
}
public void run()
{
while (true)
{
if (x==0)
r.setResource("zhangsan","nan");
else
r.setResource("lisi","nv");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while (true)
{
r.outResource();
}
}
} |
|