java ArrayQueue数据队列的使用

来源:互联网 发布:淘宝宝贝详情怎么设置 编辑:程序博客网 时间:2024/05/01 05:01

package com.coship.mes.stbsdk.apis;

/**
 * 数组队列,该队列在创建时可以不指定队列最大容量,如果没有指定队列最大容量,则会采用默认的最大容量(500)
 *
 */
class ArrayQueue {
 private static final int MAX_SIZE = 500;
 private Object[] queue; // 队列
 private int front;      // 头指针
 private int rear;       // 尾指针
 private int length;     // 队列初始化长度
 
 private Object lock = new Object();
 
 /**
  * 构造函数
  *
  */
 ArrayQueue() {
  this(MAX_SIZE);
 }
 
 /**
  * 构造函数
  *
  * @param length 队列最大长度
  */
 ArrayQueue(int length) {
  this.length = length;
  queue = new Object[this.length + 1];
  front = rear = 0;
 }

 /**
  * 增加一个指定的元素到队列中,如果要添加的元素超出了队列容量的限制时会抛出异常
  *
  * @param object 要添加的元素
  * @return true---添加成功
  * @throws IllegalStateException 如果由于容量限制无法添加指定元素
  */
 boolean add(Object object) throws IllegalStateException {
  if (offer(object))
   return true;
  else
   throw new IllegalStateException("Queue full");
 }
 
 /**
  * 增加一个指定的元素到队列中
  *
  * @param object 要添加的元素
  * @return true---添加成功,false---队列满
  * @throws NullPointerException 要添加的元素为NULL
  */
 boolean offer(Object object) {
  synchronized (lock) {
   if (object == null)
    throw new NullPointerException();
   
   if (isFull())
    return false;

   queue[rear] = object;
   rear = (rear + 1) % queue.length;
   
   lock.notifyAll();
   
   return true;
  }
 }

 /**
  * 检索并移除队列的第一个元素,该方法在队列为空时会阻塞,直到会拿到队列元素为止
  *
  * @return 队列的第一个元素
  */
 Object take() {
  synchronized (lock) {
   if (isEmpty())
    try {
     lock.wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   
   return poll();
  }
 }
 
 /**
  * 检索并移除队列的第一个元素
  *
  * @return 队列的第一个元素,当队列为空时则为NULL
  */
 Object poll() {
  if (isEmpty()) {
   return null;
  }
  
  Object object = queue[front];
  queue[front] = null; // 释放对象
  front = (front + 1) % queue.length;
  
  return object;
 }

 /**
  * 清空队列
  *
  */
 void clear() {
  queue = null;
  queue = new Object[this.length + 1];
  front = rear = 0;
 }

 /**
  * 获得队列当前大小
  *
  * @return
  */
 int size() {
  return (rear - front + queue.length) % queue.length;
 }
 
 /**
  * 获取队列容量
  *
  * @return
  */
 int capacity() {
  return this.length;
 }

 /**
  * 判断队列是否已满
  *
  * @return
  */
 boolean isFull() {
  return (rear + 1) % queue.length == front;
 }

 /**
  * 判断队列是否为空
  *
  * @return
  */
 boolean isEmpty() {
  return front == rear;
 }
}

0 0