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();
}
}
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();
}
}
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]根本就没有分配内存.所以会出现这样的错误丫