日期:2014-05-20 浏览次数:20912 次
class Test
{
public static void main(String args[])
{
Queen q=new Queen();
Producer pr=new Producer(q);
Consumer c=new Consumer(q);
pr.run();
c.run();
}
}
class Producer extends Thread
{
Queen q;
Producer(Queen q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<=10;i++)
{
q.put(i);
}
}
}
class Consumer extends Thread
{
Queen q;
Consumer(Queen q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
class Queen
{
int value;
boolean bNull=true;
public synchronized void put(int i)
{
if(bNull)
{
this.value=i;
bNull=false;
System.out.print("put:"+i);
notify();
}
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public synchronized void get()
{
if(bNull)
{
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("get:"+value);
bNull=true;
notify();
}
}
pr.run();
c.run();
pr.start();
c.start();