/* * 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 MStart * @email m_start@163.com */public class FIFOTest { /** * @param args the command line arguments */ public static void main(String[] args) { FIFO fifo = new FIFOImpl(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 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 FIFOextends List , Deque , Cloneable, java.io.Serializable { /** * 向最后添加一个新的,如果长度超过允许的最大值,则弹出一个 * */ T addLastSafe(T addLast); /** * 弹出head,如果Size = 0返回null。而不同于pop抛出异常 * @return */ T pollSafe(); /** * 获得最大保存 * * @return */ int getMaxSize(); /** * 设置最大存储范围 * * @return 返回的是,因为改变了队列大小,导致弹出的head */ List setMaxSize(int maxSize);}class FIFOImpl extends LinkedList implements FIFO { 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 setMaxSize(int maxSize) { List list = null; if (maxSize < this.maxSize) { list = new ArrayList (); 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 + '}'; }}