JAVA入门
百度了大量资料后写了个简单消息处理队列
Node 是自己仿写的链表,参考LinkedList
至于为啥要仿写感觉学习阶段重复轮子肯定是必不可少的事情。。
package org.great.server.model;
import org.great.common.model.Msg;
import org.great.common.model.Node;
/**
*
* @author Blless 利用线程阻塞写的消息处理队列 感觉写完这个事件监听也可以写了
*
*/
public class MsgQueue extends Thread {
private boolean Running;
public Node<Msg> msgList;
private static MsgQueue mq = null;
private MsgQueue() {
this.Running = true;
this.msgList = new Node<Msg>();
start();
}
synchronized public static MsgQueue getInstance() {
if (mq == null) {
mq = new MsgQueue();
}
return mq;
}
@Override
public void run() {
while (Running) {
if (msgList.isEmpty()) {// 链表是否为空
synchronized (this) {
try {
// for debug
System.out.println("Waitting...");
// debug end
this.wait();// 空则阻塞线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
msgList.getFirst();
Process();
msgList.delFirst();
}
}
}
public void close() {
this.Running = false;
interrupt();
}
public void putMsg(Msg msg) {
msgList.add(msg);
synchronized (this) {
// for debug
System.out.println("Notify...");
// debug end
notify();
}
}
private void Process() {
// for debug
System.out.println("Running...");
// debug end
}
}
测试
package org.great.server.model;
import org.great.common.model.Msg;
/**
*
* @author Blless 消息队列测试类
*
*/
public class TestQueue {
public static void main(String[] args) {
MsgQueue mq = MsgQueue.getInstance();
Msg msg =new Msg();
while(true){
try {
Thread.sleep(1000);
mq.putMsg(msg);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}