简体   繁体   English

遍历linkedBlockingQueue并同时删除元素

[英]iterating over linkedBlockingQueue and removing elements at the same time

My code is as follows: 我的代码如下:

private LinkedBlockingQueue<TrackedOperation> operations = new LinkedBlockingQueue<TrackedOperation>(10000);
        Iterator<TrackedOperation> it = operations.iterator();
        while (it.hasNext()) {
            TrackedOperation op = operations.remove();
                            ...
        }

My question is: 我的问题是:

Would iterator be always pointing to the head of the queue and is that the expected behavior? 迭代器是否总是指向队列的头部,这是预期的行为吗?

If I am not making sense, then my question is what would be the behavior of iterator? 如果我没有道理,那么我的问题是迭代器的行为是什么? Is my operations queue and iterator consistent in the above code? 我的操作队列和迭代器在以上代码中是否一致?

Here what I do, 我在这里做什么

while (!linkedBlockingQueue.isEmpty()) {
    linkedBlockingQueue.remove(); //do what you want to with it
}

You can only call it.remove() after you've called it.next(). 调用it.next()之后,只能调用它。 The element returned by it.next() is the one that will then be removed by the it.remove() operation. 由it.next()返回的元素是将由it.remove()操作删除的元素。

Accepting @assylias answer above 接受上面的@assylias答案

You would generally while(true) E e = queue.take(); 您通常while(true)E e = queue.take(); with a blocking queue. 与阻塞队列。 Then interrupt the thread or send a special item to break the loop 然后中断线程或发送特殊项目以中断循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM