I'm new to java and I'm trying to implement simple producer consumer problem. Below is the code that i've written to test it. I have 3 classes, Main class, producer class and consumer class. Now the problem is my producer is producing the data but my consumer is not consuming it. Could anybody please explain me why this is happening. Thanks in advance.
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();
}
}
}