class Res
{
private String name;
private String sex;
private boolean flag=false;
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 Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
boolean b=true;
while(true)
{
if(b)
{
r.set("zhangsan", "man");
b=false;
}
else
{
r.set("张三", "男");
b=true;
}
}
}
}
class Outer implements Runnable
{
private Res r;
Outer(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
public class InputOutputDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Res r=new Res();
Input in=new Input(r);
Outer out=new Outer(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
这个程序用单例 该怎么做?求高手!谢谢! |