public void out()
{
lock.lock();
while(!bl)
try{out_cn.wait();}catch(InterruptedException e){}
System.out.println("姓名:"+this.name+"性别:"+this.sex);
bl = false;
in_cn.signal();
lock.lock();
}
}
//创建一个输出对象
class InputDemo implements Runnable
{
private boolean flag= true;
Person p;
InputDemo(Person p)
{
this.p=p;
}
public void run()
{
while(true)
{
if(flag)
{p.set("小强","男");flag=false;}
else{p.set("弱弱","女");flag=true;}
}
}
}
//创建一个输出对象
class Output implements Runnable
{
Person p ;
Output(Person p)
{
this.p = p;
}
public void run()
{
while(true){
p.out();
}
}
}
class ThReenTrant
{
public static void main(String[] args)
{
Person p = new Person();
InputDemo in = new InputDemo(p);
Output out = new Output(p);
Thread t = new Thread(in);
Thread t1 = new Thread(in); //两个访问者
Thread t2 = new Thread(out);
Thread t3 = new Thread(out); //两个输出者
t.start();
t1.start();
t2.start();
t3.start();