I have 90 IDs that I need to something like on the image below. I want the last ID to be popped first and if there are new IDs added to the stack I want to push them on the end of it. Last In 开发者_开发知识库Last Out. Does something like this exists already? I know I could use other collection implementations but I wonder if there is a stack like this already made.
Queue is an interface with multiple implementations (including such things as blocking queues suitable for multi-threaded solutions)
You probably want to have a FIFO (first-in-first-out)
queue.
First have a look at Javadoc from java.util.Queue.
There exist several implementations:
- java.util.LinkedList
- java.util.concurrent.LinkedBlockingQueue
- java.util.concurrent.ArrayBlockingQueue
You could use a Queue<E>
.
looks like a normal queue implementation, with the elements added to the queue in reverse order to start off with.
You may use sort of a Queue<E>
implementation which is provided by java (see queue implementations).
Another possible Option would be to use a LinkedList<E>
(see.: http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html)
It offers all methods you need. Especially because your description seems so if you are not totally sure about the behavior you want.
A Queue<E>
should be preferred over a LinkedList<E>
at least for large collections without the need of random access.
Here's some code to get you started:
private static BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
public static void main(String args[]) throws InterruptedException {
// Start a thread that puts stuff on the queue
new Thread(new Runnable() {
public void run() {
while (true) {
try {
queue.put("Some message");
Thread.sleep(100);
}
catch (InterruptedException e) {
// Handle interruption
}
}
}
}).start();
// Start a thread that takes stuff from the queue (LILO)
new Thread(new Runnable() {
public void run() {
while (true) {
try {
String message = queue.take(); // Waits if necessary for something to arrive
// Do something with message
Thread.sleep(100);
}
catch (InterruptedException e) {
// Handle interruption
}
}
}
}).start();
Thread.currentThread().wait();
}
精彩评论