当前位置: 代码迷 >> Java相关 >> 生产者与消费者,这里出现什么问题
  详细解决方案

生产者与消费者,这里出现什么问题

热度:361   发布时间:2011-11-04 19:57:59.0
生产者与消费者,这里出现什么问题
程序代码:

public class PandC {

    /**
     *
@param args
     
*/
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Procedure procedure  = new Procedure();
        Custom  custom = new Custom();
        procedure.start();
        custom.start();

    }

}


class Baozi{
    int id;
    Baozi(int id){
        this.id=id;
    }
    public String toString (){
        return ":"+id;
    }
}


class Panel{
    int index=0;
    Baozi[] baozi =new Baozi[10];
   
    public synchronized void inPut(Baozi bz){
        while(index==baozi.length){
            
                 try {
                     System.out.println("等待消费中~~~~~~~~");
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            
        }
        this.notify();
        
        baozi[index]=bz;
        index++;
         
    }
   
public synchronized Baozi outPut(){
   
    while(index==0){
        
             try {
                 System.out.println("等该生产中~~~~~~~~");
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         }
      this.notify();
      index--;
        return baozi[index];
    }
   
   
}

//生产者

class Procedure extends Thread{
    private Panel p= new Panel();
     public void run(){
        //for(int i=p.index;i<p.baozi.length;i++){
        for(int i=0;i<30;i++){
            Baozi bz = new Baozi(i);
            p.inPut(bz);
            System.out.println ("生产第"+bz+"号包子");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
   
}

//消费者
class Custom extends Thread{
    private Panel p= new Panel();
     public void run(){
        //for(int i=p.index;i>=0;i--){
        for(int i=0;i<30;i++){   
            Baozi bz=p.outPut();
            System.out.println ("消费第"+bz+"号包子");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
}
搜索更多相关的解决方案: color  消费者  生产者  procedure  

----------------解决方案--------------------------------------------------------
提示: 作者被禁止或删除 内容自动屏蔽
2011-11-04 16:06:24
lucky563591

等 级:小飞侠
威 望:4
帖 子:765
专家分:2103
注 册:2009-11-18
  得分:2 
先看看书上的例子去模仿。
----------------解决方案--------------------------------------------------------
回复 2楼 付政委
还在拿你那鸡店的程序。。。。。。。
----------------解决方案--------------------------------------------------------
  相关解决方案