package com.MessageQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class MessageQueue {
private static BlockingQueue<MessageBean> blockingQueue;
private static MessageQueue messageQueue;
private MessageQueue() {
// 规定BlockingQueue的容量
blockingQueue = new LinkedBlockingQueue<MessageBean>(100);
}
public static MessageQueue getInstance() {
if (messageQueue == null) {
synchronized (MessageQueue.class) {
if (messageQueue == null) {
messageQueue = new MessageQueue();
}
}
}
return messageQueue;
}
/**
* 查看当前BlockingQueue的容量
*
* @return
*/
public int getMessageVol() {
if (blockingQueue != null) {
return blockingQueue.size();
}
return 0;
}
/**
* 向BlockingQueue中放入指定的对象
*
* @param message
*/
public void put(MessageBean message) {
try {
blockingQueue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 从BlockingQueue中提取指定对象
*
* @return
*/
public MessageBean take() {
try {
MessageBean message = blockingQueue.take();
return message;
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
当然是创建对象的Bean类
package com.MessageQueue;
public class MessageBean {
private int messageId;
private String messageContext;
public MessageBean(int messageId, String messageContext) {
this.messageId = messageId;
this.messageContext = messageContext;
}
public int getMessageId() {
return messageId;
}
public void setMessageId(int messageId) {
this.messageId = messageId;
}
public String getMessageContext() {
return messageContext;
}
public void setMessageContext(String messageContext) {
this.messageContext = messageContext;
}
}
第三步.
创建BloackingQueue的测试类来检验是否成功
package com.MessageQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MessageQueueTest implements Runnable {
private static MessageQueue messageQueue;
public static void main(String[] args) {
// TODO Auto-generated method stub
messageQueue = MessageQueue.getInstance();
MessageQueueTest thread = new MessageQueueTest();
ExecutorService executorService = Executors.newCachedThreadPool();
for (int a = 1; a <= 10; a++) {
executorService.submit(thread);
}
for (int i = 0; i < 200; i++) {
MessageBean messagebean = new MessageBean(i, "The first message!");
messageQueue.put(messagebean);
}
System.out.println("Now the message Queue size:" + messageQueue.getMessageVol());
}
@Override
public void run() {
while (true) {
MessageBean getBean = messageQueue.take();
System.out.println(getBean.getMessageId() + " : " + getBean.getMessageContext());
System.out.println("Now the message Queue size:" + messageQueue.getMessageVol());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
从测试类中,我使用了多线程的方式去读取BlockingQueue中的数据,主要是为了测试BlockingQueue是否是真正是线程安全的和容量参数是否真的能够实现。
经过测试,的确如此。