Java简单实现固定长度队列(FIFO)

时间:2021-12-01 17:41:13
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package linkedlisttest;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
*
* @author Vicky.H
* @email eclipser@163.com
*/
public class FIFOTest {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
FIFO<A> fifo = new FIFOImpl<A>(5);
for (int i = 0; i < 20; i++) {
A a = new A("A:" + i);
A head = fifo.addLastSafe(a);
System.out.println(i + "\thead:" + head + "\tsize:" + fifo.size());
}

System.out.println("---------------");

System.out.println("弹出数据");
List<A> polls = fifo.setMaxSize(3);
for (A a : polls) {
System.out.println("\thead:" + a);
}

System.out.println("剩余数据");
for (A a : fifo) {
System.out.println("\thead:" + a);
}
System.out.println(fifo.size());
}
}

interface FIFO<T> extends List<T>, Deque<T>, Cloneable, java.io.Serializable {

/**
* 向最后添加一个新的,如果长度超过允许的最大值,则弹出一个 *
*/
T addLastSafe(T addLast);

/**
* 弹出head,如果Size = 0返回null。而不同于pop抛出异常
* @return
*/
T pollSafe();

/**
* 获得最大保存
*
* @return
*/
int getMaxSize();

/**
* 设置最大存储范围
*
* @return 返回的是,因为改变了队列大小,导致弹出的head
*/
List<T> setMaxSize(int maxSize);

}

class FIFOImpl<T> extends LinkedList<T> implements FIFO<T> {

private int maxSize = Integer.MAX_VALUE;
private final Object synObj = new Object();

public FIFOImpl() {
super();
}

public FIFOImpl(int maxSize) {
super();
this.maxSize = maxSize;
}

@Override
public T addLastSafe(T addLast) {
synchronized (synObj) {
T head = null;
while (size() >= maxSize) {
head = poll();
}
addLast(addLast);
return head;
}
}

@Override
public T pollSafe() {
synchronized (synObj) {
return poll();
}
}

@Override
public List<T> setMaxSize(int maxSize) {
List<T> list = null;
if (maxSize < this.maxSize) {
list = new ArrayList<T>();
synchronized (synObj) {
while (size() > maxSize) {
list.add(poll());
}
}
}
this.maxSize = maxSize;
return list;
}

@Override
public int getMaxSize() {
return this.maxSize;
}
}

class A {

private String name;

public A() {
}

public A(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "A{" + "name=" + name + '}';
}
}


run:
0 head:null size:1
1 head:null size:2
2 head:null size:3
3 head:null size:4
4 head:null size:5
5 head:A{name=A:0} size:5
6 head:A{name=A:1} size:5
7 head:A{name=A:2} size:5
8 head:A{name=A:3} size:5
9 head:A{name=A:4} size:5
10 head:A{name=A:5} size:5
11 head:A{name=A:6} size:5
12 head:A{name=A:7} size:5
13 head:A{name=A:8} size:5
14 head:A{name=A:9} size:5
15 head:A{name=A:10} size:5
16 head:A{name=A:11} size:5
17 head:A{name=A:12} size:5
18 head:A{name=A:13} size:5
19 head:A{name=A:14} size:5
---------------
弹出数据
 head:A{name=A:15}
 head:A{name=A:16}
剩余数据
 head:A{name=A:17}
 head:A{name=A:18}
 head:A{name=A:19}
3
成功构建 (总时间: 0 秒)