1、继承LinkedBlockingQueue
public class TestQueue extends LinkedBlockingQueue<String>{}LinkedBlockingQueue和LinkedList一样,内部基于链表来存放元素,实现了BlockingQueue接口。LinkedBlockingQueue不指定队列容量时,默认为Integer.MAX_VALUE,即无界队列,为了避免队列过大造成机器负载或者内存爆满,建议手动传一个队列的大小。LinkedBlockingQueue构造函数可以显式的指定队列的大小。如下:
public LinkedBlockingQueue(int capacity) { if (capacity <= 0) throw new IllegalArgumentException(); this.capacity = capacity; last = head = new Node<E>(null); }TestQueue 可以按照如下方式定义队列大小:
public TestQueue(int capacity){super(capacity);}2、初始化队列
public static TestQueue queue = null; public static void init() { if (null != queue) { return; } queue = new ImageKeyQueue(); }3、将内容添加至队列中
public static void putInfo(String key) { if (null == queue) { return; } try { queue.put(key); } catch (InterruptedException e) { e.printStackTrace(); } }4、从队列中获取数据并移除
public static String takeInfo() { if (null == queue) { return null; } try { if (queue.size() == 0) { return null; } return (String) queue.take(); } catch (InterruptedException e) { e.printStackTrace(); } return null; }5、获取队列当前容量
public static int getSize() { return queue.size(); }