BlackMamba
BlackMamba

Reputation: 10252

why the program hang up when using ArrayBlockingQueue

I'm having an issue when using an ArrayBlockingQueue.

Here is my code:

package study;

import org.pmw.tinylog.Logger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class App {
    public static void main(String[] args) throws Exception {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        Thread.sleep(1000);
    }
}

class Producer implements Runnable {
    protected BlockingQueue<String> queue = null;

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 100000; i++) {
                queue.put(String.valueOf(i));
                //Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            Logger.info(e);
        }
    }
}

class Consumer implements Runnable {
    protected BlockingQueue queue;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            Logger.info(queue.take());
            //Logger.info(queue.take());
            //Logger.info(queue.take());
        } catch (InterruptedException e) {
            Logger.info(e);
        }
    }
}

But the output is:

2016-10-24 14:08:27 [Thread-1] study.Consumer.run()
INFO: 0

I don't think this is correct, but I can't find the problem.

Upvotes: 0

Views: 588

Answers (2)

T.Tony
T.Tony

Reputation: 515

You run

Logger.info(queue.take());

only once, as a result, the consumer exit after getting ONE '0' from the queue. Just add a while loop like

while(true) {
    Logger.info(queue.take());
}

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44844

Change your Consumer's run to loop as at the moment you are only taking the first element off the queue, whilst the Producer has put 100000 into the queue.

 public void run() {
  while (true) {
    try {
        Logger.info(queue.take());
        //Logger.info(queue.take());
        //Logger.info(queue.take());
    } catch (InterruptedException e) {
        Logger.info(e);
    }
  }
}

Upvotes: 1

Related Questions