参考学习封装Queue队列,先进先出

最近由于项目需求,参考有关的代码,学习封装了一个队列
主要技术点:
1. 进入队列,需要判断是否isFull(),
2. 出队列, 需要判断isEmpty(),
3. 队列允许插入任何对象
4. 最后一个知识点就是lock.lock(), finally{lock.unlock()}
每次相关操作就需要进行加锁和解锁


/**
*
*/
package util;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* @author Administrator
*
*/
public class Queue<Element> {
int arraySize;
private Element[] data;
private int first;
private int next;

Lock lock = new ReentrantLock();

public Queue(int size) {
// TODO Auto-generated constructor stub
arraySize = size;

empty();
}

/**
* 队列复位
* 关键是创建Element数组做data
* first, last = 0
*/
private void empty() {
// TODO Auto-generated method stub
lock.lock();

try{
data = (Element[]) new Object[arraySize];
first = 0;
next = 0;
}
finally{
lock.unlock();
}
}

/**
* 算法,计算队列的数组
* @return
*/
public int size(){

lock.lock();
try{
return (arraySize - first + next ) % arraySize;
}
finally{
lock.unlock();
}

}

/**
* 判断first, last的index是否相同?
* @return
*/
public boolean isEmpty() {
// TODO Auto-generated method stub
lock.lock();

try{
return (first == next);
}
finally{
lock.unlock();
}
}

/**
* 返回是否为空
* @return
*/
public boolean isFull(){
lock.lock();

try{
if(size() == (arraySize - 1)){
return true;
}
return false;
}
finally{
lock.unlock();
}
}

/**
* 关键算法
* data[next] = input 新插入数据放入data
* next = next+1 % arraySize
* @param socketSession
*/
public void enQueue(Element input) {
// TODO Auto-generated method stub
lock.lock();

try{
if(isFull()){
throw new RuntimeException("over flow");
}
data[next] = input;
next = (next + 1) % arraySize;
}
finally{
lock.unlock();
}
System.out.println("store socketsession");
}

/**
* 出队列算法,获取第一个元素
* 1. 判断是否为空队列
* 2. 去除第一个元素, element = data[first];
* 3. data[first]=null, 该位置附上空值
* 4. first++, 如果>=arraySize, first=0;
* @return
*/
public Element deQueue(){
Element result = null;
lock.lock();

try{

if(isEmpty()){
throw new RuntimeException("queue is empty");
}

result = data[first];
data[first] = null;

first++;

if(first >= arraySize){
first = 0;
}

return result;
}
finally{
lock.unlock();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值