刚学JAVA,生产消费者问题,求指点

Coffee_Home 2016-07-25 10:52:16
RT,这是我的程序, 为什么运行结果总是先消费了一个馒头。。。才开始生产消费正常化。。难道是我的WAIT和NOTIFY用的不对嘛?
public class WQ{
public static void main(String [] args){
LanZi lz = new LanZi();
Producer p = new Producer(lz);
Consumer c = new Consumer(lz);
new Thread(p).start();
new Thread(c).start();
}
}

class ManTou{
int id;
ManTou(int id){
this.id = id;
}

public String toString(){
return "ManTou" + id;
}
}

class LanZi{
ManTou[] arrMT = new ManTou[6];
int index = 0;

public synchronized void jia(ManTou MT){
while(index==arrMT.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
arrMT[index] = MT;
index++;
}

public synchronized ManTou jian(){
while(index==0){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
index--;
return arrMT[index];
}
}

class Producer implements Runnable{
LanZi lz = null;
Producer(LanZi lz){
this.lz = lz;
}

public void run(){
for(int i=0;i<20;i++){
ManTou mt = new ManTou(i+1);
lz.jia(mt);
System.out.println("生产了"+mt);
/* try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
*/
}
}
}

class Consumer implements Runnable{
LanZi lz = null;
Consumer(LanZi lz){
this.lz = lz;
}

public void run(){
for(int i=0;i<20;i++){
ManTou mt = lz.jian();
System.out.println("消费了"+mt);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
...全文
180 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
adfldk 2016-07-26
  • 打赏
  • 举报
回复
你馒头是装在篮子里
nikyotensai 2016-07-26
  • 打赏
  • 举报
回复
new Thread(p).start(); new Thread(c).start(); 中间加Thread.sleep(1000); p可能还没开始c就开始了

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧