本帖最后由 小太阳大开心 于 2014-6-30 11:29 编辑
class Rec
{
private String name;
private String sex;
private boolean flag;
public synchronized void set(String name,String sex)
{
if (flag)
{
try
{
this.wait();
}
catch (Exception e)
{
}
}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out()
{
if (flag)
{
try
{
this.wait();
}
catch (Exception e)
{
}
}
System.out.println(name+"......"+sex);
flag=false;
this.notify();
}
}
class Input implements Runnable
{
private Rec r;
Input(Rec r)
{
this.r=r;
}
public void run()
{
int x=0;
while (true)
{
if (x==0)
{
r.set("baixue","man");
}
else
r.set("cxy","girl");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Rec r;
Output(Rec r)
{
this.r=r;
}
public void run()
{
while (true )
{
r.out();
}
}
}
class InputOutputDemo2
{
public static void main(String[] args)
{
Rec r=new Rec();
new Thread (new Input(r)).start();
new Thread( new Output(r)).start();
}
}
|
|