Java:尝试将对象添加到 BlockingQueue 时出现 NullPointerException?

发布于 2024-12-05 18:04:16 字数 200 浏览 1 评论 0原文

我发现了一个关于 PriorityQueue 的类似问题,该问题的错误是它没有正确初始化。我可能有同样的问题,但我不知道如何正确初始化它!

截至目前,我只是这样做:

BlockingQueue myQueue = null;

但当我尝试向列表中添加某些内容时,就会抛出异常。

如何正确初始化 BlockingQueue?

I found a similar question about a PriorityQueue, the error with that one was that it wasn't initialized correctly. I might have the same problem, but i can't figure out how to initialize it correctly!

As of now i just do:

BlockingQueue myQueue = null;

but that throws an exception as soon as i try to add something to the list.

How do i correctly initialize a BlockingQueue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烏雲後面有陽光 2024-12-12 18:04:16

BlockingQueue 是一个接口。您需要选择该接口的特定实现,例如 ArrayBlockingQueue,并调用其 构造函数像这样:

BlockingQueue<E> myQueue = new ArrayBlockingQueue<E>(20);

如果您不确定 JDK 中存在哪些不同类型的阻塞队列,请查看 “所有已知的实现类”

BlockingQueue<E> is an interface. You need to pick a specific implementation of that interface, such as ArrayBlockingQueue<E>, and invoke one of its constructors like so:

BlockingQueue<E> myQueue = new ArrayBlockingQueue<E>(20);

If you're unsure what different types of blocking queues exist in the JDK, look under "All Known Implementing Classes".

蝶舞 2024-12-12 18:04:16

如果您对 null 调用任何方法,您将收到空指针异常。
尝试创建一个新的 ArrayBlockingQueue,它实现该接口。

If you call any method on null you will get a null pointer exception.
Try making a new ArrayBlockingQueue, which implements the interface.

所有深爱都是秘密 2024-12-12 18:04:16

请阅读 javadocs,其中也有示例
http://download.oracle.com/javase /6/docs/api/java/util/concurrent/BlockingQueue.html

BlockingQueue 阻塞队列 =
新的ArrayBlockingQueue(100); // 还有其他实现,特别是使用链表并且比数组具有更好的扩展性。

Please read the javadocs which also has examples
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html

BlockingQueue blockingQueue =
new ArrayBlockingQueue(100); // there are other implementations as well, in particular that uses a linked list and scales better than the array one.

浅唱々樱花落 2024-12-12 18:04:16
  1. BlockingQueue 保存某种类型,例如 BlockingQueue 或类似的东西。
  2. 您需要使用 BlockingQueue 的实现来初始化该变量,例如 ArrayBlockingQueue

所以做一些类似的事情:

BlockingQueue<MyObject> = new ArrayBlockingQueue<MyObject>();

你会没事的。

  1. Make BlockingQueue hold a certain type, for example BlockingQueue<String> or something similar.
  2. You need to initialize the variable with an implementation of BlockingQueue, for example ArrayBlockingQueue<E>.

So do something like:

BlockingQueue<MyObject> = new ArrayBlockingQueue<MyObject>();

and you'll be fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文