BlockingQueue 和 TransferQueue 的区别
我对 BlockingQueue/LinkedBlockingQueue 与 jsr166y 和 java 7 中的新 TransferQueue/LinkedTransferQueue 类型之间的区别有点困惑
I am a little bit confused as to what the difference is between BlockingQueue/LinkedBlockingQueue and the new TransferQueue/LinkedTransferQueue types from jsr166y and java 7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 TransferQueue JavaDocs:
换句话说,当你使用BlockingQueue时,你只能将元素放入队列(如果队列已满则阻塞)。使用 TransferQueue,您还可以阻塞直到其他线程收到您的元素(您必须为此使用新的
transfer
方法)。这就是区别。使用 BlockingQueue,您不能等到其他线程删除您的元素(仅当您使用 SynchronousQueue 时,但这并不是真正的队列)。除此之外,TransferQueue也是一个BlockingQueue。查看 TransferQueue 中新的可用方法: http:// /download.oracle.com/javase/7/docs/api/java/util/concurrent/TransferQueue.html(传输、tryTransfer、hasWaitingConsumer、getWaitingConsumerCount)。
Java SE 7 中的集合框架增强功能明确表示:
From TransferQueue JavaDocs:
In other words, when you use BlockingQueue, you can only put element into queue (and block if queue is full). With TransferQueue, you can also block until other thread receives your element (you must use new
transfer
method for that). This is the difference. With BlockingQueue, you cannot wait until other thread removes your element (only when you use SynchronousQueue, but that isn't really a queue).Other than this, TransferQueue is also a BlockingQueue. Check out new available methods in TransferQueue: http://download.oracle.com/javase/7/docs/api/java/util/concurrent/TransferQueue.html (transfer, tryTransfer, hasWaitingConsumer, getWaitingConsumerCount).
Collections Framework Enhancements in Java SE 7 says explicitly:
简而言之,BlockingQueue 保证了生产者生成的元素必须在队列中,而 TransferQueue 则更进一步,它保证了该元素被某个消费者“消费”。
In short, BlockingQueue guarantees that the element made by producer must be in the queue, while TransferQueue gets one step further, it guarantees that the element "consumed" by some consumer.
很久以前的一个问题,@Peter 的回答非常详尽。对于想了解 TransferQueue 在实际中如何工作的人,也许可以参考下面的现场演示。
输出是:
transfer
是差异发生的地方。与 javadoc 一样,
传输
将等到消费者拿走产品为止。这就是为什么首先调用
"Producer waiting to transfer: 0"
,大约 2 秒后,消费者收到后,Producer Transfered: 0
是然后打电话。A question long time ago and @Peter's answer is really elaborate. For people who wants to know how TransferQueue works in practice, maybe you can refer to the live demo below.
The output is:
The
transfer
is where the difference happens.As the javadoc, the
transfer
will wait until the consumer has taken the product away.That's the reason why
"Producer waiting to transfer: 0"
is called firstly and after about 2 seconds, after it has been received by the consumer, theProducer transfered: 0
is called then.尽管似乎确实存在某种形式的性能差异;请参阅 ArrayBlockingQueue 与 LinkedTransferQueue 和朋友
Although there does seem to be some form of performance difference; see ArrayBlockingQueue vs LinkedTransferQueue and friends