我是java新手,我正在尝试实现简单的生产者消费者问题。下面是我为测试它而编写的代码。我有 3 个类,主要类,生产者类和消费者类。现在的问题是我的生产者正在生产数据,但我的消费者没有消费它。谁能解释一下为什么会这样。提前致谢。
public class ProducerConsumerWithQueue {
/**
* @param args
*/
public static void main(String[] args) {
ArrayList<String > queue = new ArrayList<String>();
Producer producer = new Producer( queue);
Consumer consumer = new Consumer( queue);
consumer.start();
producer.start();
}
}
public class Producer extends Thread{
ArrayList<String> queue;
public Producer(ArrayList<String> queue) {
this.queue = queue;
}
public void run(){
System.out.println("Producer Started");
System.out.println("Producer size "+queue.size());
for(int i=0;i<50;i++){
try {
synchronized (this) {
if(queue.size()>10){
System.out.println("Producer Waiting");
wait();
}else{
System.out.println("producing "+i);
queue.add("This is "+i);
notifyAll();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Consumer extends Thread{
ArrayList<String> queue;
public Consumer(ArrayList<String> queue) {
this.queue = queue;
}
public void run(){
System.out.println("Consumer started");
System.out.println("Consumer size "+queue.size());
try {
synchronized (this) {
for(int i=0; i>10; i++){
if(queue.isEmpty()){
System.out.println("Consumer waiting()");
wait();
}else{
System.out.println("Consuming Data "+queue.remove(i));
notifyAll();
}
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}