日期:2014-05-20  浏览次数:20662 次

Java 多线程典型的生产者与消费者问题,有些不理解,请指教。

   写的是生产和消费包子的问题,一个四个实体类:生产者,消费者,包子,篮子,篮子可以装6个包子,不过运行结果不是预想中的那样,会出现生产7个包子后开始消费的情况,还有第一次消费基本都会从第一个开始消费,可预想是像栈那样后进先出的,不知道哪里出问题了,请指教~~~
   还有,生产和消费两个类中添加延时,就是文中注释掉的部分,结果貌似会和预想的相近一些。
    练习写的代码,还没养成写注释的习惯,抱歉~~~~


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;
}
}


运行结果: