问一个Producer-Consumer模型问题
学java没多久,学操作系统,想模拟进程不同步问题,写了个Producer-Consumer程序:
但结果很怪,consumer老是在下标为-1抛出异常,大家能否帮我看看程序,可以在自己的机器上运行看看:多谢了!
class Goods{
private int[] a; //used as the container
private int index=0; //indicate how many goods are there in the container
private int iput=0; //pointer used to put good to the container
private int iget=0; //pointer used to get good from the container
Goods(){
a=new int[30];
}
public void put(int i){
int nextiput=(iput+1)%30;
if(nextiput==iget){
System.out.println("Sorry the Container is full,you can't put good to the container!");
System.exit(0);
}
else{
int ip=iput;
System.out.println("Successfully stored "+i+" to the number: "+iput+" space");
iput=(iput+1)%30;
a[iput]=i;
index++;
}
}
public void get(){
if(iput==iget){
System.out.println("Sorry the Container is empty,you can't get good from the container!");
System.exit(0);
}
else{
int good=a[iget];
int inx=iget;
iget=(iget-1)%30;
index--;
System.out.println("Successfully get "+good+" from space "+inx);
}
}
}
class Producer extends Thread{
private Goods g;
Producer(Goods g){
this.g=g;
}
public void run(){
for(int i=0; i<10; i++){
g.put(i);
try{
Thread.sleep((int)(Math.random()*100));
}catch(Exception e){}
}
}
}
class Consumer extends Thread{
private Goods g;
Consumer(Goods g){
this.g=g;
}
public void run(){
for(int i=0; i<10; i++){
g.get();
try{Thread.sleep((int)(Math.random()*1000));}
catch(Exception e){}
}
}
}
class main{
public static void main(String[] args){
Goods g=new Goods();
Producer p=new Producer(g);
Consumer c=new Consumer(g);
p.start();
c.start();
}
}