java LinkedList 学习

 

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();
	    }
	}

    }
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值