gpt4 book ai didi

java - LinkedBlockingQueue 和 addAll()

转载 作者:行者123 更新时间:2023-12-03 16:24:13 30 4
gpt4 key购买 nike

如果尝试向阻塞队列添加超过阻塞队列剩余大小的集合,会发生什么?从我目前阅读的文档中并不清楚这一点。

     LinkedBlockingQueue<Integer> foo = new LinkedBlockingQueue<Integer>(3);
foo.add(1);
foo.add(2);
LinkedBlockingQueue<Integer> tenElements = new LinkedBlockingQueue<Integer(10);
for(int i = 0; i < 10; i++)
tenElements.add(i);

foo.addAll(collectionWith10elements);

最佳答案

add() 的文档声明 IllegalStateException如果队列已满则抛出:

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.



当您尝试以下代码时:
public static void main(String[] args) throws Exception {
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(50);
LinkedBlockingQueue<Integer> foo = new LinkedBlockingQueue<Integer>(3);
foo.add(1);
foo.add(2);
foo.addAll(l);
}

您将收到以下异常:
Exception in thread "main" java.lang.IllegalStateException: Queue full
at java.util.AbstractQueue.add(AbstractQueue.java:98)
at java.util.AbstractQueue.addAll(AbstractQueue.java:187)
at Test.main(Test.java:16)

关于java - LinkedBlockingQueue 和 addAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59473123/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com