package com.qq.util;
import java.util.concurrent.*;
/**
* a <code> MessageDeque<T> </code> 定义了阻塞式的消息队列
*
* @version 1.0
* @author mark
*/
public class MessageQueue<T> {
/*
* 阻塞队列
*/
private BlockingQueue<T> m_queue = null;
/**
* 构造函数,必须指定消息队列的最大容量
*
* @param maxitem
* 消息队列的最大容量
*/
MessageQueue(int maxitem) {
m_queue = new LinkedBlockingQueue<T>(maxitem);
}
/**
* 得到当前队列项目数目
*
* @return 当前队列项目数目
*/
public int getcount() {
return m_queue.size();
}
/**
* 清空队列
*
* @return
*
*/
public void clear() {
m_queue.clear();
}
/**
* 得到当前队列头项目
*
* @return 当前队列头项目
*/
public T get() {
return m_queue.poll();
}
/**
* 得到当前队列头项目
*
* @param timeoutmillisecond
* 超时时间
* @return 当前队列头项目
* @see #get()
*/
public T get(long timeoutmillisecond) throws InterruptedException {
return m_queue.poll(timeoutmillisecond, TimeUnit.MILLISECONDS);
}
/**
* 放入队列尾元素
*
* @return 成功为true,失败为false,失败一般是队列满
* @see #put(Object, long)
*/
public boolean put(T item) throws InterruptedException {
return m_queue.offer(item);
}
/**
* 放入队列尾元素
*
* @param item
* 超时时间
* @return 成功为true,失败为false,失败一般是队列满
* @see #put(Object)
*/
public boolean put(T item, long timeoutmillisecond)
throws InterruptedException {
return m_queue.offer(item, timeoutmillisecond, TimeUnit.MILLISECONDS);
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
MessageQueue<String> msg = new MessageQueue<String>(4);
msg.put("aaaaaa");
msg.put("bbbbbb");
msg.put("ccccccc");
msg.put("ddddddd");
msg.put("eeeeeee");
while (msg.getcount() > 0) {
System.out.println(msg.get());
}
}
}