Blocking Queue在Java中有哪些优势? [英] What are the advantages of Blocking Queue in Java?

查看:122
本文介绍了Blocking Queue在Java中有哪些优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用队列保存有关需要发送到远程主机的消息的信息的项目。在这种情况下,一个线程负责将信息放入队列,另一个线程负责从队列中获取信息并发送它。第二个线程需要定期检查队列信息。

I am working on a project that uses a queue that keeps information about the messages that need to be sent to remote hosts. In that case one thread is responsible for putting information into the queue and another thread is responsible for getting information from the queue and sending it. The 2nd thread needs to check the queue for the information periodically.

但是后来我发现这是重新设计的轮子:)我可以使用阻塞队列来实现这个目的。

But later I found this is reinvention of the wheel :) I could use a blocking queue for this purpose.

在上述应用程序中使用阻塞队列的其他优点是什么? (例如:性能,可修改代码,任何特殊技巧等)

What are the other advantages of using a blocking queue for the above application? (Ex : Performance, Modifiable of the code, Any special tricks etc )

推荐答案

主要优点是一个 BlockingQueue 提供了一个正确的,线程安全的实现。开发人员自己已经实施了这个功能了很多年了,但是很难得到正确的结果。现在运行时已经由并发专家开发,审查和维护了一个实现。

The main advantage is that a BlockingQueue provides a correct, thread-safe implementation. Developers have implemented this feature themselves for years, but it is tricky to get right. Now the runtime has an implementation developed, reviewed, and maintained by concurrency experts.

队列的阻塞性质有几个优点。首先,在添加元素时,如果队列容量有限,内存消耗也是有限的。此外,如果队列消费者远远落后于生产者,生产者自然会被节制,因为他们必须等待添加元素。当从队列中获取元素时,主要优点是简单;等待永远是微不足道的,正确等待指定的超时只是一点点复杂。

The "blocking" nature of the queue has a couple of advantages. First, on adding elements, if the queue capacity is limited, memory consumption is limited as well. Also, if the queue consumers get too far behind producers, the producers are naturally throttled since they have to wait to add elements. When taking elements from the queue, the main advantage is simplicity; waiting forever is trivial, and correctly waiting for a specified time-out is only a little more complicated.

这篇关于Blocking Queue在Java中有哪些优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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