生产者与消费者

class  Producer  implements  Runnable
{
Q  q;
Producer(Q q)
{
this.q=q;
}
public void   run()
{
int i=0;
while(true)
{
synchronized(q)
{
if(i==0)
{
q.name="Zhangsan";
try
{
Thread.sleep(1);
}
catch(Exception e)
{}
q.sex="male";

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

class  Consumer  implements   Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
}
public  void  run()
{
while(true)
{
synchronized(q)
{
System.out.print(q.name);
System.out.println(":"+q.sex);
}
}
}
}

class  Q
{
String  name="unknown";
String  sex="unknown";
}

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:04  平安夜  阅读(102)  评论(0编辑  收藏  举报