生产者与消费者,这里出现什么问题
程序代码:
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(); } } } }