package testjava.thread;
public class SellBuy {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Q q = new Q();
new Thread(new Producer(q)).start();
new Thread(new Comsumer(q)).start();
}
}
class Producer implements Runnable
{
Q q;
public Producer(Q q)
{
this.q=q;
}
public void run()
{
int i=0;
while(true)
{
if(i==0)
q.put("zhangsan","male");
else
q.put("lisi","femail");
i=(i+1)%2;
}
}
}
class Comsumer implements Runnable
{
Q q;
public Comsumer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
class Q
{
String name="unknown";
String sex="unkonwn";
boolean bFull=false;
public synchronized void put(String name,String sex)
{
if(bFull)
try {wait();} catch (Exception e) {}
this.name=name;
try {Thread.sleep(1);} catch (Exception e) {}
this.sex=sex;
bFull=true;
notify();
}
public synchronized void get()
{
if(!bFull)
try {wait();} catch (Exception e) {}
System.out.println(name+":"+sex);
bFull=false;
notify();
}
}