队列已满,在阻塞队列的深度,需要澄清 [英] Queue Full, On depth of the Blocking Queue, clarification needed

查看:253
本文介绍了队列已满,在阻塞队列的深度,需要澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从文件内容填充队列时,深度似乎不会增加,因为此实现中未添加元素。

When populating the queue from the contents of the file, depth does not seem to ever increase, as elements are not added in this implementation.

    BlockingQueue<String> q = new SynchronousQueue<String>();
            ...
        fstream = new FileInputStream("/path/to/file.txt");
            ...
        while ((line = br.readLine()) != null) {
            if (q.offer(line))
                System.out.println("Depth: " + q.size()); //0
        }

当替换 offer with add ,抛出异常

When replacing offer with add, exception if thrown

Exception in thread "main" java.lang.IllegalStateException: Queue full
  ...

我在做什么错了吗?插入第一个元素后,为什么队列立即满了?

What am i doing wrong please? Why is the queue full immediately, upon insertion of the first element?

推荐答案

检查文档 SynchronousQueue


一个阻塞队列,其中每个put必须等待一个take,反之亦然。同步队列没有任何内部容量,甚至没有容量。您无法查看同步队列,因为只有在您尝试接受该元素时才会出现该元素; 你不能添加一个元素(使用任何方法),除非另一个线程试图删除它;你不能迭代,因为没有什么可以迭代。队列的头部是第一个排队线程尝试添加到队列的元素;如果没有排队的线程,则不添加任何元素,并且head为null。出于其他Collection方法(例如contains)的目的,SynchronousQueue充当空集合。此队列不允许使用null元素。

A blocking queue in which each put must wait for a take, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to take it; you cannot add an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued thread is trying to add to the queue; if there are no queued threads then no element is being added and the head is null. For purposes of other Collection methods (for example contains), a SynchronousQueue acts as an empty collection. This queue does not permit null elements.

在尝试添加到队列之前,需要让消费者进行设置和等待。

You need to have consumers set up and waiting before you can try to add to the queue.

如果没有消费者, offer 方法不会做任何事情:

The offer method doesn't do anything if there are no consumers:


将指定的元素插入此队列,如果另一个线程正在等待接收它。

这篇关于队列已满,在阻塞队列的深度,需要澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆