BlackMamba BlackMamba - 1 month ago 11
Java Question

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.

Answer

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);
    }
  }
}