日拱一卒:队列(Queue)

2023-02-03  本文已影响0人  Tinyspot

1. 队列(Queue)

1.1 常用方法

while (!queue.isEmpty()) {
    System.out.println(queue.poll());
}

public class QueueDemo<E> {
    // 使用双向链表
    private List<E> linkedList = new LinkedList<>();
    public boolean offer(E element) {
        return linkedList.add(element);
    }
    public E poll() {
        // 队头出队,index=0
        return linkedList.remove(0);
    }
    public int size() {
        return linkedList.size();
    }
    public boolean isEmpty() {
        return linkedList.isEmpty();
    }
}

2. 用栈实现队列

public class QueueByStack<E> {
    private Stack<E> inStack = new Stack<>();
    private Stack<E> outStack = new Stack<>();

    public boolean isEmpty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }

    public E offer(E element) {
        return inStack.push(element);
    }

    public E poll() {
        checkOutStack();
        return outStack.pop();
    }

    public E peek() {
        checkOutStack();
        return outStack.peek();
    }

    public void checkOutStack() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
    }

}

3. 阻塞队列(BlockedQueue)

3.1 等待 - 通知机制

参考:极客时间 - Java 并发编程实战 - 06 用“等待-通知”机制优化循环等待

3.2 Lock + Condition 实现阻塞队列

3.3 LinkedBlockingQueue

上一篇下一篇

猜你喜欢

热点阅读