You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中构造含15个元素的同步BlockingQueue列表?

问题原因

你代码里的new ArrayList<>(15)只是为ArrayList设置了初始容量(底层数组的大小),但并没有实际向列表中添加任何元素,所以列表的size()返回0是正常的。

解决方案

要得到包含15个空ArrayBlockingQueue<AtomicInteger>的同步列表,需要手动向列表中添加15个队列实例,以下是两种可行方式:

方式一:循环添加元素

List<BlockingQueue<AtomicInteger>> listOfQueues = 
    Collections.synchronizedList(new ArrayList<>(15));

// 循环添加15个空的ArrayBlockingQueue
for (int i = 0; i < 15; i++) {
    // 可根据需求指定ArrayBlockingQueue的容量,示例中用100,可自行调整
    listOfQueues.add(new ArrayBlockingQueue<>(100));
}

方式二:使用Stream API(Java 8及以上)

如果想用更简洁的写法,可借助Stream生成元素:

List<BlockingQueue<AtomicInteger>> listOfQueues = 
    Collections.synchronizedList(
        Stream.generate(() -> new ArrayBlockingQueue<AtomicInteger>(100))
              .limit(15)
              .collect(Collectors.toCollection(() -> new ArrayList<>(15)))
    );

注意:ArrayBlockingQueue的构造必须指定容量,示例中用了100,你可以根据实际业务场景调整这个数值。

内容的提问来源于stack exchange,提问作者curiousMind_85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:35:50