对于 BlockingQueue/LinkedBlockingQueue 与来自 jsr166y 和 java 7 的新 TransferQueue/LinkedTransferQueue 类型之间的区别我有点困惑
最佳答案
A BlockingQueue in which producers may wait for consumers to receive elements. A TransferQueue may be useful for example in message passing applications in which producers sometimes (using method transfer(E)) await receipt of elements by consumers invoking take or poll, while at other times enqueue elements (via method put) without waiting for receipt.
换句话说,当你使用 BlockingQueue 时,你只能将元素放入队列(如果队列已满则阻塞)。使用 TransferQueue,您还可以阻塞直到其他线程收到您的元素(您必须为此使用新的 transfer
方法)。这就是区别。使用 BlockingQueue,您不能等到其他线程删除您的元素(仅当您使用 SynchronousQueue 时,但这并不是真正的队列)。
除此之外,TransferQueue 也是一个 BlockingQueue。查看 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明确地说:
The interface TransferQueue has been added. It is a refinement of the BlockingQueue interface in which producers can wait for consumers to receive elements. One implementation of the new interface is also included in this release, LinkedTransferQueue.
关于java - BlockingQueue 和 TransferQueue 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7317579/