【发布时间】:2018-08-12 09:52:02
【问题描述】:
我有一个简单的 ArrayBlockingQueue 测试如下:
public class TestQueue {
static class Producer implements Runnable {
private ArrayBlockingQueue<Integer> queue;
private int index;
public Producer(ArrayBlockingQueue<Integer> queue, int index) {
this.queue = queue;
this.index = index;
}
@Override
public void run() {
try {
queue.put(index);
System.out.println("producer: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Consumer implements Runnable {
private ArrayBlockingQueue<Integer> queue;
public Consumer(ArrayBlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while(true) {
System.out.println("consumer: " + queue.take());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
for (int i = 0; i < 10; i++) {
Producer producer = new Producer(queue, i);
new Thread(producer).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Consumer consumer = new Consumer(queue);
new Thread(consumer).start();
}
}
结果是:
producer: 2
producer: 0
producer: 1
consumer: 0
producer: 4
producer: 6
consumer: 2
etc...
我的问题是,我已经定义了ArrayBlockingQueue的大小为3,而生产者已经将2、0和1,总共3个项目放入队列中,现在队列已经满了,那么消费者已经消费了0,现在队列的大小应该是2,然后生产者将4放入队列,现在队列应该已满,为什么生产者仍然可以将6放入队列,应该是阻塞了
【问题讨论】:
-
问题出在打印中,
System.out.printlnis not thread safe 所以看起来该值已插入到一个完整的队列中。 -
@Guy 为什么要责备
System.out.println?它是线程安全的。
标签: java multithreading queue producer-consumer blockingqueue