我写了一个生产者消费者的程序,我希望手动输入缓冲区大小。下面是我写的程序,每次运行到我输入完数据就没反映了,请大家看看。
package ture;
import java.util.*;
public class PNCTest {
public static void main(String args[]){
    PNC stack=new PNC();
     Scanner in=new Scanner(System.in);
     System.out.println("输入缓冲区大小");
     int s=in.nextInt();
     stack.setBuffer(s);
     stack.getBuffer();
Runnable p=new Producer(stack);
Runnable q=new Consumer(stack);
Thread t1=new Thread(p);
Thread t2=new Thread(q);
t1.start();
t2.start();
}
}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
package ture;
import java.util.*;
public class PNC {
private int index=0;
public  int ;public void setBuffer(int s){
this.buffer=s;
}
public int getBuffer(){
return buffer;
}
char[] data=new char[buffer];
public synchronized void push(char c) {
while(index==data.length){
try{
this.wait();
}catch(InterruptedException e){}
}
this.notify();
data[index]=c;
index++;
System.out.println("生产:"+c);
}
public synchronized char pop(){
while(index==0){
try{
this.wait();
}catch(InterruptedException e){}

}
this.notify();
index--;
System.out.println("消费:"+data[index]);
return data[index];
}}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
package ture;public class Producer implements Runnable {
PNC stack;
public Producer(PNC s){
stack=s;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
char c=(char)(Math.random()*26+'A');
stack.push(c);
try{Thread.sleep((int)(Math.random()*300));
}catch(InterruptedException e){e.printStackTrace();
}
  }
}}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
package ture;public class Consumer implements Runnable {
PNC stack;
public Consumer(PNC s){
stack=s;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
char c=stack.pop();
try{
Thread.sleep((int)(Math.random()*800));
}catch(InterruptedException e){e.printStackTrace();}

}
}}

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主【dujolon】截止到2008-06-28 22:55:08的历史汇总数据(不包括此帖):
    发帖数:8                  发帖分:150                
    结贴数:7                  结贴分:130                
    未结数:1                  未结分:20                 
    结贴率:87.50 %            结分率:86.67 %            
    楼主加油