一、采用链表实现队列
public class MyQueue { private class Node { public Node before; public Object data; public Node after; public Node(Node before, Object data, Node after) { this.before = before; this.data = data; this.after = after; } } /** * 头节点 */ private Node head; /** * 尾节点 */ private Node tail; public MyQueue() { head = new Node(null, null, null); tail = new Node(null, null, null); head.after = tail; tail.before = head; } /** * 入队列 * @param o */ public void push(Object o) { Node n = new Node(null, o, null); Node n1 = tail.before; tail.before = n; n1.after = n; n.before = n1; n.after = tail; } /** * 出队列 * @return */ public Object pop() { Node after = head.after; Node n = after.after; head.after = n; n.before = head; return after; }}
二、使用队列实现生产者消费者模式
public class Producer implements Runnable { private MyQueue queue; public Producer(MyQueue queue) { this.queue = queue; } @Override public void run() {// while(true) {// queue.push(Math.random());// } }}public class Consumer implements Runnable { private MyQueue queue; public Consumer(MyQueue queue) { this.queue = queue; } @Override public void run() {// while (true) {// Object o = queue.pop();// } }}public class Main { public static void main(String[] args) { MyQueue queue = new MyQueue(); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); Thread t1 = new Thread(producer); Thread t2 = new Thread(consumer); t1.start(); t2.start(); }}