Date: 2012may14
Update: 2025sep22
Language: Java
Level: novice
Q. Java: Best way to enumerate a LinkedBlockingQueue
A. Here is a full example:
import java.util.concurrent.LinkedBlockingQueue;
class Demo {
static LinkedBlockingQueue<String> gQueue = new LinkedBlockingQueue<String>();
public static final void main(String []args) throws Exception {
gQueue.put("one");
gQueue.put("two");
gQueue.put("three");
for (String item : gQueue) {
System.out.println("item=" + item);
}
}
}
Output:
item=one
item=two
item=three
What if the queue is changed during your loop?
That seems to be taken care of my the LinkedBlockingQueue.
Or you could make a lock to protect the entire loop.