JAVA线程问题,新手求教

w_windy 2013-10-22 06:13:47
看视频然后自己写的一个比较简单的生产者消费者问题,发现有时还没生产就能消费了。。。求教,谢谢




public class RunCandP {

public static void main(String[] args) {
pot P1 = new pot();
consumer C1 = new consumer(P1);
cooker Co1 = new cooker(P1);
new Thread(Co1).start();
new Thread(C1).start();
}

}

public class consumer implements Runnable {
pot P = null;
public consumer(pot P){
this.P = P;
}
public void run(){
for (int f=0;f<20;f++){
P.get();
System.out.println("吃了面包"+bread.all+" "+P.index);
}
}
}

public class cooker implements Runnable {
pot P =null;
public cooker(pot P){
this.P=P;
}
public void run(){
for(int f=0;f<20;f++){
P.add(new bread());
System.out.println("生产了"+bread.all+" "+P.index);
}
}

}


public class pot {

bread[] p=new bread[6];
int index=0;

public synchronized void add(bread a){
try{
while (index == p.length) {
System.out.println("停止生产,等待中...");
this.wait();
}}catch(InterruptedException e) {
System.out.println("添加出错。");
}
this.notify();
p[index]=a;
index++;
}



public synchronized bread get(){
try {
while (index == 0) {
System.out.println("没有得吃了,等待生产...");
this.wait();
}}catch(InterruptedException e){
System.out.println("消费出错。");
}
this.notify();
bread a = this.p[index];
this.p[index]=null;
index--;
return a;
}
}



public class bread {
static int all=0;
bread(){
all++;
}
public String toString() {
return "bread:"+"第"+all+"个";
}
}


...全文
223 5 打赏 收藏 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
w_windy 2013-10-23
  • 打赏
  • 举报
回复
自己再查了下解决啦,因为没把输出语句放在锁定区域,所以出现执行完生产还没输出就跳到消费线程里面,把他改到里面就好了。。不好意思
w_windy 2013-10-23
  • 打赏
  • 举报
回复
引用 2 楼 soton_dolphin 的回复:
在consumer 里面你需要检测BREAD[] 是不是为空 在COOKER 里面你需要检测BREAD[]是不是已经满了
在add和get里面有检测。
Birds2018 2013-10-22
  • 打赏
  • 举报
回复
int index=0; 这个前面加 violate int index=0; while (index == p.length) 这个建议改成 while (index >= p.length) while (index == 0) 这个建议改成 while (index <= 0) this.notify(); p[index]=a; index++; 这个地方你把顺序改一下, p[index]=a; index++; this.notify();
soton_dolphin 2013-10-22
  • 打赏
  • 举报
回复
在consumer 里面你需要检测BREAD[] 是不是为空 在COOKER 里面你需要检测BREAD[]是不是已经满了
Defonds 2013-10-22
  • 打赏
  • 举报
回复

62,620

社区成员

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

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