在javadoc中,我看到addAll
对BlockingQueue
不是线程安全的,所以我认为以下代码不是线程安全的,但我运行了很长时间,而不是异常抛出有人可以解释一下吗?感谢
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());
}
}
}
}