class Dome
{
public String name;
public String sex;
public boolean flag=false;
public synchronized void set(String name,String sex)
{
if(this.flag)
try{this.wait();}catch(Exception e){}
this.name=name;
this.sex=sex;
this.flag=true;
this.notify();
}
public synchronized void out()
{
if(!this.flag)
try{this.wait();}catch(Exception e){}
System.out.println("姓名:"+this.name+"---------性别:"+this.sex);
this.flag=false;
this.notify();
}
}
class InputDome implements Runnable
{
public Dome d;
InputDome(Dome d)
{
this.d=d;
}
public void run()
{
//int i=0;
boolean f=true;
while(true)
{
if(f)
{
d.set("weixiaohui", "man");
f=false;
}
else
{
d.set("魏晓晖", "男");
d.name="魏晓晖";
d.sex="男";
f=true;
}
}
/*while(true)
{
synchronized(d)
{
if(d.flag)
try{d.wait();}catch(Exception e){}
if(f)
{
d.name="weixiaohui";
d.sex="man";
f=false;
}
else
{
d.name="魏晓晖";
d.sex="男";
f=true;
}
d.flag=true;
d.notify();
//i=(i+1)%2;
}
}*/
}
}
class OutputDome implements Runnable
{
public Dome d;
OutputDome(Dome d)
{
this.d=d;
}
public void run()
{
while(true)
{
d.out();
}
/*while(true)
{
synchronized(d)
{
if(!d.flag)
try{d.wait();}catch(Exception e){}
System.out.println("姓名:"+d.name+"---------性别:"+d.sex);
d.flag=false;
d.notify();
}
}*/
}
}
public class InputOutputDome {
/**
* @param args
*/
public static void main(String[] args) {
Dome d=new Dome();
Thread t1=new Thread(new InputDome(d));
Thread t2=new Thread(new OutputDome(d));
t1.start();
t2.start();
}
}
大神不要笑哈,初来乍到,多多关照 |
|