簡體   English   中英

遍歷linkedBlockingQueue並同時刪除元素

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

我的代碼如下:

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

我的問題是:

迭代器是否總是指向隊列的頭部,這是預期的行為嗎?

如果我沒有道理,那么我的問題是迭代器的行為是什么? 我的操作隊列和迭代器在以上代碼中是否一致?

我在這里做什么

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

調用it.next()之后,只能調用它。 由it.next()返回的元素是將由it.remove()操作刪除的元素。

接受上面的@assylias答案

您通常while(true)E e = queue.take(); 與阻塞隊列。 然后中斷線程或發送特殊項目以中斷循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM