日期:2014-05-20 浏览次数:20708 次
public class Produce
{
public static void main(String[] args)
{
Barsket b=new Barsket();
Pro p=new Pro(b);
Cus c=new Cus(b);
new Thread(p).start();
new Thread(c).start();
}
}
//生产者
class Pro implements Runnable
{
Barsket b;
Pro(Barsket b)
{
this.b=b;
}
public void run()
{
for (int i=1;i<=20 ; i++)
{
/*try
{
Thread.sleep((int)(Math.random()*200));
}
catch (InterruptedException e)
{
e.printStackTrace();
}*/
Bao bao=new Bao(i);
b.produce(bao);
System.out.println("生产了 "+bao.toString());
}
}
}
//消费者
class Cus implements Runnable
{
Barsket b;
Cus(Barsket b)
{
this.b=b;
}
public void run()
{
for (int i=1;i<=20 ; i++)
{
/*try
{
Thread.sleep((int)(Math.random()*200));
}
catch (InterruptedException e)
{
e.printStackTrace();
}*/
Bao bao=b.consume();
System.out.println("消费了 "+bao.toString());
}
}
}
//篮子,可以放6个包子
class Barsket
{
int index =0;
Bao bao[]=new Bao[6];
static int num=0;
public synchronized void produce(Bao baozi)
{
while(index==6)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.notifyAll();
bao[index]=baozi;
index++;
//return bao[index];
}
public synchronized Bao consume()
{
while(index==0)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.notifyAll();
index--;
return bao[index];
}
}
//包子类
class Bao
{
int i;
Bao(int i)
{
this.i=i;
}
public String toString()
{
return "包子:"+i;
}
}