package com.voole.queun;
/**
* @Decription 队列
* @author TMAC-J
*
*/
public class Queun {
/**
* 初始化队列尺寸
*/
private int queunSize = 0;
/**
* 初始化头指针
*/
private int front = -1;
/**
* 初始化尾指针
*/
private int rear = 0;
/**
* 声明数组
*/
private int[] array;
/**
* 当前大小
*/
private int curentSize = 0;
/**
* 构造方法
* @param queunSize
*/
public Queun(int queunSize){
this.queunSize = queunSize;
array = new int[this.queunSize];
}
/**
* 读操作
*/
public synchronized void read(){
if(!isEmpty()){
front = (front+1)%queunSize;
       array[front] = null;
curentSize--;
}
else{
System.out.println("当前队列为空!");
/**
* 优化CPU时间片的利用率,若当前队列为空会切换到另外的线程,不会继续执行此线程浪费时间和空间
*/
try {
this.notifyAll();//唤醒其他所有线程
this.wait();//释放对象锁,将当前线程置为阻塞
this.notify();//唤醒当前线程
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("front"+front);
}
/**
* 写操作
* @param data
*/
public synchronized void write(int data){
if(!isFull()){
array[rear] = data;
rear = (rear+1)%queunSize;
curentSize++;
}
else{
System.out.println("当前队列已满");
try {
this.notifyAll();
this.wait();
this.notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("rear"+rear);
} /**
* 判断是否是满
*/
public boolean isFull(){
if(curentSize == queunSize){
return true;
}
else{
return false;
}
}
/**
* 判断是否是空
*/
public boolean isEmpty(){
if(curentSize == 0){
return true;
}
else{
return false;
}
}
  

   public Object getQueunHead(){
      return array[(front+1)%queunSize];
      }

}
package com.voole.queun;

public class Test {

    public static void main(String[] args) {
Queun queun = new Queun(10);
Thread writeThread = new Thread(new WriteThread(queun));
writeThread.start();
Thread readThread = new Thread(new ReadThread(queun));
readThread.start();
} private static class ReadThread implements Runnable{
private Queun queun;
public ReadThread(Queun queun){
this.queun = queun; }
@Override
public void run() {
int i = 100;
if(queun!=null){
while(i>0){
queun.read();
// System.out.println("read"+i);
i--;
}
}
}
} private static class WriteThread implements Runnable{
private Queun queun;
public WriteThread(Queun queun){
this.queun = queun;
}
@Override
public void run() {
int i = 100;
if(queun!=null){
while(i>0){
queun.write(i);
// System.out.println("write"+i);
i--;
}
}
}
}
}

现在在实习,每天也就改改bug,利用闲暇时间,研究一下数据结构,收货还是蛮大的,这是队列的优化java代码实现方式。如果还有什么想要了解的,可以参考一下http://blog.csdn.net/sinat_33713995/article/details/51331314和https://zhidao.baidu.com/question/1947170630893457148.html

这两篇解释的比较详细

04-17 07:19