请教为什么会出现数据越界,谢谢

uqortbsa 2010-05-17 04:46:18
public class Stop{
public static void main(String args[]){
GRcart s=new GRcart();
new Thread(s).start();

new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();



}

}
class Cart{
int id;
Cart(int id){
this.id=id;
}
public int getId(){
return id;
}
public String toString(){
return id+"Cart";
}
}
class GRcart implements Runnable{
int cart[]=new int[100];
public GRcart(){
for(int i=0;i<100;i++)
cart[i]=i+1;
}



public synchronized void pop(){
int index=100;
while(index<0){
try{
this.wait();

}catch(InterruptedException e){
e.printStackTrace();
}
}

this.notify();
Cart c=new Cart(cart[index--]);
System.out.println(c.getId()+"号车被推出去了");


try{
Thread.sleep(1000);
}catch(InterruptedException e){}


System.out.println(c.getId()+"号车已经推回来了");
cart[++index]=c.getId();


}






public void run(){
pop();



}

}



...全文
272 6 打赏 收藏 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
charles361 2010-05-17
  • 打赏
  • 举报
回复
return id+"Cart"; 应该写成"Cart" + id吧
Mars_Ma_OK 2010-05-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 q331464542 的回复:]
Java code

int cart[]=new int[100];
public GRcart(){
for(int i=0;i<100;i++)
cart[i]=i+1;
}



Java code

Cart c=new Cart(cart[index--]……
[/Quote]

楼上正解..
跟着Mic学架构 2010-05-17
  • 打赏
  • 举报
回复

int cart[]=new int[100];
public GRcart(){
for(int i=0;i<100;i++)
cart[i]=i+1;
}


Cart c=new Cart(cart[index--]);

LZ请仔细检查一下,前面你通过构造函数初始化的最大数组下标到了cart[99],而你再看下面的代码
Cart c =new Cart(cart[index--])
index初始化值为100,index--的含义是先使用完100这个数值后再减1,所以cart[index]为cart[100]
而cart[100]根本就没有分配内存.所以会出现这样的错误丫
茫茫大海 2010-05-17
  • 打赏
  • 举报
回复
楼主,上面的说错了!问题出在 Cart c=new Cart(cart[index--]);和 cart[++index]=c.getId();处,改为 Cart c=new Cart(cart[--index]);和cart[index++]=c.getId();就好了!
茫茫大海 2010-05-17
  • 打赏
  • 举报
回复
问题应该出在 while(index<0){,改为while(index>0),就不会报数组越界异常了!
yulinkhdy 2010-05-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 q331464542 的回复:]

Java code

int cart[]=new int[100];
public GRcart(){
for(int i=0;i<100;i++)
cart[i]=i+1;
}


Java code

Cart c=new Cart(cart[index--]);


LZ请……
[/Quote]


正解。。

62,620

社区成员

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

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