赞
踩
非阻塞方式:直接拒绝
阻塞方式:将请求排入队列内,等待空闲线程
PS:链表/数组队列的特性
基于链表的队列,支持无界队列(unbounded queue),但是会导致过多请求排队,请求处理的响应时间过程,因此对于时间敏感的系统不适用。
基于数组的队列,能实现有界队列(bounded queue),队列长度有限制,使用时需要合理安排队列的大小,充分利用资源
先进先出,入队enqueue,出队dequeue
队列也是一种操作受限的线性表数据结构
具有额外特性的队列:
循环队列、阻塞队列、并发队列
顺序队列:用数组实现
链式队列:用链表实现
PS:在用数组实现队列时,随着dequeue操作,head指针会向后移动,当队列没有空间时,如果head指针的“前边”还有空间,则集中进行一次数据搬移,且时间复杂度仍旧是O(1),详见下列代码。
// 用数组实现的队列(定长数组,长度n,队头下标head,队尾下标tail) public class ArrayQueue { // 数组:items,数组大小:n private String[] items; private int n = 0; // head表示队头下标,tail表示队尾下标 private int head = 0; private int tail = 0; // 申请一个大小为capacity的数组 public ArrayQueue(int capacity) { items = new String[capacity]; n = capacity; } // 入队,不带数据搬移 public boolean enqueue(String item) { // 如果tail == n 表示队列已经满了 if (tail == n) return false; items[tail] = item; ++tail; return true; } // 出队 public String dequeue() { // 如果head == tail 表示队列为空 if (head == tail) return null; // 为了让其他语言的同学看的更加明确,把--操作放到单独一行来写了 String ret = items[head]; ++head; return ret; } } // 带集中数据搬移功能的enqueue public boolean enqueue(String item) { // tail == n表示队列末尾没有空间了 if (tail == n) { // tail ==n && head==0,表示整个队列都占满了 if
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。