In the javadoc, I saw the addAll
is not thread safe for BlockingQueue
, so I suppose the following code is not thread safe, but I run it for a long time, and not exception throw, could anyone explain that ? Thanks
public class Test {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
new Producer(queue).start();
new Consumer(queue).start();
}
public static class Producer extends Thread {
private LinkedBlockingQueue<String> queue;
public Producer(LinkedBlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; ++i) {
list.add(i + "");
}
this.queue.addAll(list);
}
}
}
public static class Consumer extends Thread {
private LinkedBlockingQueue<String> queue;
public Consumer(LinkedBlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
List<String> result = Lists.newArrayList();
queue.drainTo(result);
System.out.println("Take " + result.size());
}
}
}
}