我正在为 Android 创建一个媒体播放器应用程序。我有两个线程:一个生成音频帧,另一个消耗这些帧。
我希望我的客户能够尝试使用不同大小的 ArrayBlockedQueue,从“无”缓冲(实际上是 1)到最多 10 个缓冲 block 。
我似乎在 Java 中找不到任何提供与 ArrayBlockedQueue 类似功能的类,但允许我动态地使项目列表更长/更短。
问题 1)有谁知道有一个类,其功能类似于 ArrayBlockedQueue,但允许我更改要保存的项目数量?
然后我有一个奇怪的想法:我能捏造它吗?我可以创建一个具有新大小的新 ArrayBlockedQueue,然后逐步复制旧 ArrayBlockedQueue 中当前的 1-10 个项目并将它们放入新的 ArrayBlockedQueue 中,然后将指向新 ArrayBlockedQueue 的指针存储在旧的 ArrayBlockedQueue 上吗?/p>
由于永远不会超过 10 个(或无论我的缓冲区限制是多少),因此将项目复制到新数组不会花费太多时间。
问题 2)这是一种“合理”的方法来实现 ArrayBlockedQueue 实现,并且仍然给我带来灵 active 吗?
问题3)有更好的方法来解决这个问题吗?
-肯
最佳答案
您可能需要创建自己的 BlockingQueue
实现来包装旧队列和新队列 - 从旧队列进行轮询,直到它为空,然后将其设置为 null 以防止任何内存泄漏。这样您就不会丢失旧队列上任何待处理的 put
MyBlockingQueue {
private MyBlockingQueue oldQueue
private ArrayBlockingQueue newQueue
ArrayBlockingQueue(int newCapacity, MyBlockingQueue _oldQueue) {
oldQueue = _oldQueue
newQueue = new ArrayBlockingQueue(newCapacity)
E oldVal = null
while(newQueue.remainingCapacity() > 0 &&
(oldVal = oldPoll) != null)
newQueue.put(oldVal)
}
boolean isEmpty() {
(oldQueue == null || oldQueue.isEmpty) && newQueue.isEmpty
}
void put(E e) {
newQueue.put(e)
}
E take() {
E oldVal = oldPoll
if(oldVal != null) oldVal else newQueue.take
}
E poll() {
E oldVal = oldPoll
if(oldVal != null) oldVal else newQueue.poll
}
private E oldPoll() {
// If you have more than one consumer thread, then use a temporary variable
// for oldQueue - otherwise it might be set to null between the null check
// and the call to poll
if(oldQueue == null) null
else {
E oldVal = oldQueue.poll
if(oldVal != null) oldVal
else {
oldQueue = null
null
}
}
}
}
关于java - 在 Java 中如何更改 ArrayBlockedQueue 的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249480/