I am learning java and I am implementing a basic producer-consumer usecase. I have a queue and some Producers that are inserting stuff into this queue. I also have one Consumer that implements Callable. Here is the implementation of Consumer:
public String call() throws Exception
{
while(true) {
if(!queue.isEmpty()) {
String prod = queue.poll();
System.out.println(name + " consumed " + prod);
}
}
}
Producer:
@Override
public void run() {
System.out.println("adding " + name);
queue.add(name);
}
Main:
public static void main(String[] args) {
Test();
}
public static void Test()
{
Queue<String> queue = new LinkedList<String>();
ScheduledExecutorService lots_of_producers = Executors.newScheduledThreadPool(10);
ExecutorService consumers = Executors.newFixedThreadPool(1);
for(int i=0; i<1; i++) {
Consumer consumer = new Consumer("consumer_" + i, queue);
consumers.submit(consumer);
}
for(int i=0; i<5; i++) {
Producer producer = new Producer("producer_" + i, queue);
lots_of_producers.scheduleWithFixedDelay(producer, i, 5, TimeUnit.SECONDS);
}
}
Producers work fine but the consumer doesn't work because I didn't see consumer's log.
However, if I change the consume implementation and let the consumer thread sleep when queue.isEmpty() is true, consumer works as expected.
public String call() throws Exception
{
while(true) {
if(!queue.isEmpty()) {
String prod = queue.poll();
System.out.println(name + " consumed " + prod);
} else {
Thread.sleep(100);
}
}
}
Can anybody explain why consumer thread is not working in the first case?
Also for the first case, in eclipse I can see that the consumer thread is not dead. I suspend it and it was working on this line
if(!queue.isEmpty()) {
Now if I manually step over, the consumer will work and print log. But as soon as I resume and let it run by itself, it will get stuck again.
I am trying to understand java more.
Thanks!
-Erben