使用ArrayBlockingQueue

时间:2016-10-24 06:11:44

标签: java java.util.concurrent

使用ArrayBlockingQueue时出现问题。

这是我的代码:

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

但输出是:

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

我不认为这是正确的,但我找不到问题。

2 个答案:

答案 0 :(得分:1)

Consumer的运行更改为循环,因为当您将第一个元素从队列中取出时,Producer已将 100000 放入队列

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

答案 1 :(得分:0)

你跑

Logger.info(queue.take());
因此,只有一次消费者从队列中获得一个'0'后退出。只需添加像

一样的while循环
while(true) {
    Logger.info(queue.take());
}