通知与等待

class  Producer  implements  Runnable
{
Q  q;
Producer(Q q)
{
this.q=q;
}
public void   run()
{
int i=0;

while(true)
{
synchronized(q)
{
if(q.bFull)
try{
q.wait();
}catch(Exception e){}
if(i==0)
{
q.name="Zhangsan";
try
{
Thread.sleep(1);
}
catch(Exception e)
{}
q.sex="male";

}
else
{
q.name="Lisi";
q.sex="female";
}
q.bFull=true;
q.notify();
}
i=(i+1)%2;
}
}
}

class  Consumer  implements   Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
}
public  void  run()
{
while(true)
{
synchronized(q)
{
if(!q.bFull)
try{
q.wait();
}catch(Exception  e){}
System.out.print(q.name);
System.out.println(":"+q.sex);
q.bFull=false;
q.notify();
}
}
}
}

class  Q
{
String  name="unknown";
String  sex="unknown";
boolean  bFull=false;
}

public  class  Communication
{
public   static  void  main(String []args)
{
Q q=new  Q();
new  Thread(new Producer(q)).start();
new  Thread(new Consumer(q)).start();


}
}

posted on 2012-03-10 08:31  平安夜  阅读(126)  评论(0编辑  收藏  举报