Possible Duplicate:
I am getting NullPointerException inside Consumer
Is this considered to be a bug in Producer , Consumer Scenario ??
This is my Producer class .
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Producer extends CommonClass implements Runnable {
private SyncronizedStack stack;
private int producerNum;
Producer(PriorityBlockingQueue<Character> queue) {
this.queue = queue;
}
public void run() {
char ch;
for (ch = 'a'; ch <= 'f'; ch++) {
queue.add(ch);
System.out.println("Producer" + producerNum + "produced :" + ch);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
This is my Consumer class
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Consumer extends CommonClass implements Runnable {
private int consumerNum;
Consumer(PriorityBlockingQueue<Character> queue) {
this.queue = queue;
}
public void run() {
char c;
for (int i = 0; i < 7; i++) {
try {
c = queue.take();
System.out.println("Consumer" + consumerNum + "consumed:" + c);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
This is my CommonClass
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class CommonClass {
PriorityBlockingQueue<Character> queue = null;
}
This is my Client program
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class SyncTest {
public static void main(String[] args) {
CommonClass cs = new CommonClass();
PriorityBlockingQueue<Character> queue = new PriorityBlockingQueue<Character>();
Producer p1 = new Producer(queue);
Thread t1 = new Thread(p1);
t1.start();
Consumer c1 = new Consumer(queue);
Thread ct1 = new Thread(c1);
ct1.start();
}
}
When i run this i get output as
Producer0produced :a
Consumer0consumed:a
Producer0produced :b
Consumer0consumed:b
Producer0produced :c
Consumer0consumed:c
Producer0produced :d
Consumer0consumed:d
Producer0produced :e
Producer0produced :f
Consumer0consumed:e
Consumer0consumed:f
This is in case of e and f alphabets .
Is there any problem with this output ?? as i see the statement Producer0produced two time simultaneously and then followed by Consumer0consumed statement simultaneosuly for the letters e and f .
I fear that with this code will i miss any information produced by Producer ??
Please advice ??
Thanks in advice .
Nope. Your producer thread just managed to produce a second item before the consumer managed to consume the first one. That’s entirely natural, particularly when you’re sleeping for random periods.
Of course you may want to give an upper bound to your queue – and then use
offerinstead ofaddto detect the situation where the queue was full – but the output you’ve shown is fine.