java自定义线程模型处理方法分享
看过我之前文章的园友可能知道我是做游戏开发,我的很多思路和出发点是按照游戏思路来处理的,所以和web的话可能会有冲突,不相符合。
来说说为啥我要自定义线程模型呢?
按照我做的mmorpg或者mmoarpg游戏划分,线程被划分为,主线程,全局同步线程,聊天线程,组队线程,地图线程,以及地图消息分发派送线程等;
一些列,都需要根据我的划分,以及数据流向做控制。
游戏服务器,主要要做的事情,肯定是接受玩家的 命令请求 -> 相应的操作 -> 返回结果;
在服务器端所有的消息都会注册到消息管理器里,然后消息在注册的时候会指定线程模型,
如果消息需要提交到玩家所在地图线程进行处理的话注册消息的时候就要把线程模型用(地图消息分发派送线程);
下面我们先来分析线程模型;
在看线程模型代码之前我先看看我的任务模型
package net.sz.engine.thread; import java.io.serializable; import org.apache.log4j.logger; import net.sz.engine.structs.objectattribute; import net.sz.engine.structs.objectglobal; /** * 任务模型 * * <br> * author 失足程序员<br> * mail 492794628@qq.com<br> * phone 13882122019<br> */ public abstract class taskevent implements serializable, cloneable { private static final logger log = logger.getlogger(taskevent.class); private static final long serialversionuid = 4196020659994845804l; //运行时数据 private transient final objectattribute runother = new objectattribute; //任务创建的时间 protected long createtime; //任务的唯一id protected long taskid; //取消的任务 protected boolean cancel = false; public taskevent { this.runother.put("submittime", system.currenttimemillis); createtime = system.currenttimemillis; cancel = false; taskid = objectglobal.getuuid; } public long getcreatetime { return createtime; } public void setcreatetime(long createtime) { this.createtime = createtime; } public long getsubmittime { return this.runother.getlongvalue("submittime"); } public objectattribute getrunother { return runother; } public boolean iscancel { return cancel; } public void setcancel(boolean cancel) { this.cancel = cancel; } public abstract void run; @override public object clone throws clonenotsupportedexception { return super.clone; //to change body of generated methods, choose tools | templates. } }
package net.sz.engine.thread; /** * 定时器执行器 * * <br> * author 失足程序员<br> * mail 492794628@qq.com<br> * phone 13882122019<br> */ public abstract class timertaskevent extends taskevent { private static final long serialversionuid = -8331296295264699207l; /** * 开始执行的时间 */ protected long starttime; /** * 是否一开始执行一次 */ protected boolean startaction; /** * 结束时间 */ protected long endtime; /** * 执行次数 */ protected int actioncount; /** * 间隔执行时间 */ protected int intervaltime; /** * * @param starttime 指定开始时间 * @param isstartaction 是否一开始就执行一次 * @param endtime 指定结束时间 * @param actioncount 指定执行次数 * @param intervaltime 指定间隔时间 */ public timertaskevent(long starttime, boolean isstartaction, long endtime, int actioncount, int intervaltime) { super; this.starttime = starttime; this.startaction = isstartaction; this.endtime = endtime; this.actioncount = actioncount; this.intervaltime = intervaltime; } /** * 指定任务的开始执行时间 * * @param starttime 指定开始时间 * @param isstartaction 是否一开始就执行一次 * @param actioncount 指定执行次数 * @param intervaltime 指定间隔时间 */ public timertaskevent(long starttime, boolean isstartaction, int actioncount, int intervaltime) { this(starttime, isstartaction, 0, actioncount, intervaltime); } /** * 指定结束时间已结束时间为准,执行次数不一定够 * * @param isstartaction 是否一开始就执行一次 * @param endtime 指定结束时间 * @param actioncount 指定执行次数 * @param intervaltime 指定间隔时间 * */ public timertaskevent(boolean isstartaction, long endtime, int actioncount, int intervaltime) { this(0, isstartaction, endtime, actioncount, intervaltime); } /** * 指定开始时间,和结束时间 * * @param starttime 指定开始时间 * @param endtime 指定结束时间 * @param intervaltime 指定间隔时间 */ public timertaskevent(long starttime, long endtime, int intervaltime) { this(starttime, false, endtime, -1, intervaltime); } /** * 指定的执行次数和间隔时间 * * @param actioncount 指定执行次数 * @param intervaltime 指定间隔时间 */ public timertaskevent(int actioncount, int intervaltime) { this(0, false, 0, actioncount, intervaltime); } /** * 提交后指定的时间无限制执行 * * @param intervaltime 指定间隔时间 */ public timertaskevent(int intervaltime) { this(0, false, 0, -1, intervaltime); } public long getstarttime { return starttime; } public void setstarttime(long starttime) { this.starttime = starttime; } public boolean isstartaction { return startaction; } public void setstartaction(boolean startaction) { this.startaction = startaction; } public long getendtime { return endtime; } public void setendtime(long endtime) { this.endtime = endtime; } public int getactioncount { return actioncount; } public void setactioncount(int actioncount) { this.actioncount = actioncount; } public int getintervaltime { return intervaltime; } public void setintervaltime(int intervaltime) { this.intervaltime = intervaltime; } }
这里是任务模型和定时器任务模型;
package net.sz.engine.thread; import java.util.arraylist; import java.util.list; import java.util.concurrent.concurrentlinkedqueue; import net.sz.engine.structs.objectglobal; import net.sz.engine.utils.mailutil; import net.sz.engine.utils.stringutil; import org.apache.log4j.logger; import org.jboss.jandex.main; /** * 线程模型 * <br> * author 失足程序员<br> * mail 492794628@qq.com<br> * phone 13882122019<br> */ public class threadmodel implements runnable { private static final logger log = logger.getlogger(threadmodel.class); private static long threadid = 0; protected static final object syn_object = new object; protected long tid; protected string name; protected long lastsendmail = 0; protected final arraylist<mythread> threads = new arraylist<>; /** * 任务列表 线程安全的任务列表 */ //protected final list<taskmodel> taskqueue = new arraylist<>; protected final concurrentlinkedqueue<taskevent> taskqueue = new concurrentlinkedqueue<>; /** * */ protected final list<timertaskevent> timerqueue = new arraylist<>; // false标识删除线程 protected volatile boolean runing = true; public threadmodel(threadgroup group) { this(group, "无名", 1); } public threadmodel(string name) { this(threadpool.unknownthreadgroup, name, 1); } public threadmodel(threadgroup group, string name, int threadcount) { this(group, name, threadcount, null); } public threadmodel(threadgroup group, string name, int threadcount, runnable runnable) { synchronized (syn_object) { threadid++; tid = threadid; } for (int i = 1; i <= threadcount; i++) { mythread thread; if (runnable == null) { thread = new mythread(tid, group, this, name + "-" + tid + "-" + i); } else { thread = new mythread(tid, group, runnable, name + "-" + tid + "-" + i); } thread.start; threads.add(thread); } this.name = name; } /** * 线程名字 * * @return */ public string getname { return name; } /** * 获取线程的自定义id * * @return */ public long getid { return this.tid; } /** * 增加新的任务 每增加一个新任务,都要唤醒任务队列 * * @param runnable */ public void addtask(taskevent runnable) { taskqueue.add(runnable); synchronized (taskqueue) { /* 唤醒队列, 开始执行 */ taskqueue.notifyall; } } /** * 向线程添加定时器任务 * * @param runnable */ public void addtimer(timertaskevent runnable) { synchronized (timerqueue) { if (runing) { //一开始执行一次 if (runnable.startaction) { addtask(runnable); } timerqueue.add(runnable); } else { log.error("线程已经停止"); } } } // <editor-fold defaultstate="collapsed" desc="定时器线程执行器 public void timerrun"> /** * 定时器线程执行器 */ public void timerrun { arraylist<timertaskevent> taskmodels; synchronized (timerqueue) { // 队列不为空的情况下 取出队列定时器任务 taskmodels = new arraylist<>(timerqueue); } if (!taskmodels.isempty) { for (timertaskevent timerevent : taskmodels) { int execcount = timerevent.getrunother.getintvalue("execcount"); long lasttime = timerevent.getrunother.getlongvalue("lastexectime"); long nowtime = system.currenttimemillis; if (lasttime == 0) { timerevent.getrunother.put("lastexectime", nowtime); } else if (timerevent.iscancel) { //如果任务已经取消 synchronized (timerqueue) { timerqueue.remove(timerevent); } log.debug("清理定时器任务:" + timerevent.getclass.getname); } else if (nowtime > timerevent.getstarttime // 是否满足开始时间 && (nowtime - timerevent.getsubmittime > timerevent .getintervaltime)// 提交以后是否满足了间隔时间 && (timerevent.getendtime <= 0 || nowtime < timerevent .getendtime) // 判断结束时间 && (nowtime - lasttime >= timerevent .getintervaltime)) // 判断上次执行到目前是否满足间隔时间 { // 提交执行定时器最先执行 this.addtask(timerevent); // 记录 execcount++; timerevent.getrunother.put("execcount", execcount); timerevent.getrunother.put("lastexectime", nowtime); nowtime = system.currenttimemillis; // 判断删除条件 if ((timerevent.getendtime > 0 && nowtime < timerevent.getendtime) || (timerevent.getactioncount > 0 && timerevent.getactioncount <= execcount)) { synchronized (timerqueue) { timerqueue.remove(timerevent); } log.debug("清理定时器任务:" + timerevent.getclass.getname); } } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="查看线程堆栈 public void showstacktrace"> /** * * 查看线程堆栈 */ public void showstacktrace { stringbuilder buf = new stringbuilder; for (mythread currentthread : threads) { long procc = system.currenttimemillis - currentthread.getlastexecutetime; if (procc > 5 * 1000 && procc < 864000000l) {//小于10天//因为多线程操作时间可能不准确 buf.append("线程[") .append(currentthread.getname) .append("]可能已卡死 -> ") .append(procc / 1000f) .append("s\n ") .append("执行任务:") .append(currentthread.getlastcommand.getclass.getname); try { stacktraceelement elements = currentthread.getstacktrace; for (int i = 0; i < elements.length; i++) { buf.append("\n ") .append(elements[i].getclassname) .append(".") .append(elements[i].getmethodname) .append("(").append(elements[i].getfilename) .append(";") .append(elements[i].getlinenumber).append(")"); } } catch (exception e) { buf.append(e); } buf.append("\n++++++++++++++++++++++++++++++++++"); } } string tostring = buf.tostring; if (!stringutil.isnullorempty(tostring)) { log.error(tostring); if (system.currenttimemillis - lastsendmail > 5 * 60 * 1000) { lastsendmail = system.currenttimemillis; mailutil.sendmail("线程执行已卡死 -> 游戏id-" + objectglobal.gameid + " 平台-" + objectglobal.platform + " 服务器id-" + objectglobal.serverid, tostring); } } } // </editor-fold> @override public void run { mythread currentthread = (mythread) thread.currentthread; while (runing) { while (taskqueue.isempty && runing) { try { /* 任务队列为空,则等待有新任务加入从而被唤醒 */ synchronized (taskqueue) { taskqueue.wait(500); } } catch (interruptedexception ie) { log.error(ie); } } /* 取出任务执行 */ if (runing) { currentthread.lastcommand = null; currentthread.lastcommand = taskqueue.poll; } if (currentthread.lastcommand != null) { if (currentthread.lastcommand.iscancel) { //如果任务已经取消 continue; } /* 执行任务 */ // r.setsubmittimel; currentthread.lastexecutetime = system.currenttimemillis; try { currentthread.lastcommand.run; } catch (exception e) { log.error("工人<“" + currentthread.getname + "”> 执行任务<" + currentthread.lastcommand.getclass.getname + "> 遇到错误: ", e); } long timel1 = system.currenttimemillis - currentthread.lastexecutetime; if (timel1 <= 20) { } else if (timel1 <= 100l) { log.info("工人<“" + currentthread.getname + "”> 完成了任务:" + currentthread.lastcommand.tostring + " 执行耗时:" + timel1); } else if (timel1 <= 200l) { log.info("工人<“" + currentthread.getname + "”> 长时间执行 完成任务:" + currentthread.lastcommand.tostring + " “考虑”任务脚本逻辑 耗时:" + timel1); } else { log.info("工人<“" + currentthread.getname + "”> 超长时间执行完成 任务:" + currentthread.lastcommand.tostring + " “考虑是否应该删除”任务脚本 耗时:" + timel1); } currentthread.lastexecutetime = 0; } } log.error("线程结束, 工人<“" + thread.currentthread.getname + "”>退出"); } /** * 自定义线程 */ public class mythread extends thread { /** * * @param tid 自定义线程id * @param group 分组 * @param run 执行方法 * @param name 线程名称 */ public mythread(long tid, threadgroup group, runnable run, string name) { super(group, run, name); this._id = tid; } //线程的自定义id public long _id; //正在执行的任务 public volatile taskevent lastcommand; //开始执行任务的时间 public volatile long lastexecutetime = 0; public taskevent getlastcommand { return lastcommand; } public long getlastexecutetime { return lastexecutetime; } /** * 返回线程自定义id * * @return */ @override public long getid { return _id; } } /** * 停止线程,设置线程的停止状态,并不会马上终止线程 */ public void stop { this.runing = false; } public boolean isruning { return runing; } @override public string tostring { return "thread{" + "tid=" + tid + ",name=" + this.getname + '}'; } }
我从 threadmodel 构造函数的
public threadmodel(threadgroup group, string name, int threadcount, runnable runnable) { synchronized (syn_object) { threadid++; tid = threadid; } for (int i = 1; i <= threadcount; i++) { mythread thread; if (runnable == null) { thread = new mythread(tid, group, this, name + "-" + tid + "-" + i); } else { thread = new mythread(tid, group, runnable, name + "-" + tid + "-" + i); } thread.start; threads.add(thread); } this.name = name; }
可以看出,这里我运行声明一个或者多个 mythread 线程类
为什么要这样考虑呢打个比方,如果是处理日志的写入数据这种,没有共享数据,没有线程临界区的处理流程,我可以考虑使用n个线程去处理这样的工作;不会产生脏数据;
如果是想组队请求,技能施法这种处理,我需要单队列处理,那么threadmodel里面肯定只有一个mythread 这样不算阻塞模式串行执行(或队列执行)把共享数据和线程临界区的问题也解决了不再依赖锁;
字很丑,请见谅
上面图片看出,在每一个threadmodel 里面都会两个队列,一个timertaskevent,一个是taskevent,会存在一个全局的timer thread;
全局的 timer thread 的作用是用来定时去处理和发现 threadmodel里面timertaskevent需要执行了,就把他加入到taskevent队里里面;最终执行是taskevent队列
timertaskevent为什么要存储在对应的threadmodel里面呢,那是因为比如,我a线程(threadmodel实例)运行一段时间后需要关闭,释放资源了,那么我还要去其他地方查找对应的timertask并移除掉;
package net.sz.engine.thread; import java.util.hashmap; import java.util.map; /** * * <br> * author 失足程序员<br> * mail 492794628@qq.com<br> * phone 13882122019<br> */ class timerthread extends thread { private static final object syn_object = new object; public timerthread { super(threadpool.globlthreadgroup, "global timer thread"); } @override public void run { while (true) { synchronized (syn_object) { try { syn_object.wait(2); } catch (interruptedexception ex) { } } hashmap<long, threadmodel> hashmap = new hashmap<>(threadpool.getthreadmap); for (map.entry<long, threadmodel> entryset : hashmap.entryset) { long key = entryset.getkey; threadmodel value = entryset.getvalue; value.timerrun; } } } }
线程模型的管理器
package net.sz.engine.thread; import java.util.hashmap; import java.util.concurrent.concurrenthashmap; import net.sz.engine.script.manager.scriptmanager; import net.sz.engine.timer.globtimerevent; import net.sz.engine.timer.printlnservermemorytimerevent; import org.apache.log4j.logger; /** * 线程管理器 * * <br> * author 失足程序员<br> * mail 492794628@qq.com<br> * phone 13882122019<br> */ public class threadpool { static private final logger log = logger.getlogger(threadpool.class); static public final long globlthread; static private final timerthread globltimerthread; static final long checkthreadtimerthreadmodel; static public final threadgroup globlthreadgroup = new threadgroup("global threadgroup"); static public final threadgroup unknownthreadgroup = new threadgroup(globlthreadgroup, "unknown threadgroup"); static private final concurrenthashmap<long, threadmodel> threadmap = new concurrenthashmap<>; public static void main(string[] args) { threadpool.addtimertask(globlthread, new timertaskevent(1000) { @override public void run { log.error("ssssss"); } }); } static { //创建全局线程 globlthread = addthreadmodel(globlthreadgroup, "globlthread"); //执行指定任务定时触发脚步 addtimertask(globlthread, new globtimerevent(scriptmanager.getinstance.getbasescriptentry)); //查询服务器消耗定时模型 addtimertask(globlthread, new printlnservermemorytimerevent); //创建定时器线程 globltimerthread = new timerthread; globltimerthread.start; //检查线程卡死情况 checkthreadtimerthreadmodel = addthreadmodel(globlthreadgroup, "check thread timer event"); addtimertask(checkthreadtimerthreadmodel, new checkthreadtimerevent); } /** * 删除指定id线程模型的时候回设置状态为停止状态 * * @param tid * @return */ static public threadmodel remove(long tid) { threadmodel remove = threadmap.remove(tid); if (remove != null) { remove.stop; } return remove; } /** * 获取线程池中所有线程 * * @return */ static public concurrenthashmap<long, threadmodel> getthreadmap { return threadmap; } /** * 获取线程池的一个线程 * * @param threadid * @return */ static public threadmodel getthreadmodel(long threadid) { threadmodel get = threadmap.get(threadid); if (get == null) { log.error("无法找到线程模型:" + threadid, new exception("无法找到线程模型:" + threadid)); } return get; } /** * 向线程池注册一个线程 * <br> * 默认分组 unknownthreadgroup * * @param name 线程名称 * @return */ static public long addthreadmodel(string name) { return addthreadmodel(unknownthreadgroup, name); } /** * 向线程池注册一个线程 * <br> * 默认分组 unknownthreadgroup * * @param name 线程名称 * @param threadcount 线程量 * @return */ static public long addthreadmodel(string name, int threadcount) { return addthreadmodel(unknownthreadgroup, name, threadcount); } /** * 向线程池注册一个线程 * * @param group 线程分组信息 * @param name 线程名称 * @return */ static public long addthreadmodel(threadgroup group, string name) { return addthreadmodel(group, name, 1); } /** * 向线程池注册一个线程 * * @param group 线程分组信息 * @param name 线程名称 * @param threadcount 线程量 * @return */ static public long addthreadmodel(threadgroup group, string name, int threadcount) { return addthreadmodel(group, name, null, threadcount); } /** * 向线程池注册一个线程 * * @param group 线程分组信息 * @param name 线程名称 * @param runnable * @param threadcount 线程量 * @return */ static public long addthreadmodel(threadgroup group, string name, runnable runnable, int threadcount) { threadmodel threadmodel = new threadmodel(group, name, threadcount, runnable); return addthreadmodel(threadmodel); } /** * 向线程池注册一个线程 * * @param threadmodel */ static public long addthreadmodel(threadmodel threadmodel) { threadmap.put(threadmodel.getid, threadmodel); return threadmodel.getid; } /** * 添加任务 * * @param threadid * @param task * @return */ static public boolean addtask(long threadid, taskevent task) { threadmodel threadmodel = getthreadmodel(threadid); if (threadmodel != null) { threadmodel.addtask(task); return true; } return false; } /** * 添加定时器任务 * * @param threadid * @param task * @return */ static public boolean addtimertask(long threadid, timertaskevent task) { threadmodel threadmodel = getthreadmodel(threadid); if (threadmodel != null) { threadmodel.addtimer(task); return true; } return false; } /** * 添加任务,添加任务到当前线程 * * @param task * @return */ static public boolean addcurrentthreadtask(taskevent task) { thread currentthread = thread.currentthread; if (currentthread instanceof threadmodel.mythread) { long threadid = currentthread.getid; threadmodel threadmodel = getthreadmodel(threadid); if (threadmodel != null) { threadmodel.addtask(task); return true; } } return false; } /** * 添加定时器任务,添加任务到当前线程 * * @param task * @return */ static public boolean addcurrentthreadtimertask(timertaskevent task) { thread currentthread = thread.currentthread; if (currentthread instanceof threadmodel.mythread) { long threadid = currentthread.getid; threadmodel threadmodel = getthreadmodel(threadid); if (threadmodel != null) { threadmodel.addtimer(task); return true; } } return false; } }
接下来我们看看使用情况
上篇文章中线程介绍代码
public static void main(string[] args) throws interruptedexception { //线程并行情况,有多个线程执行多个任务/函数 new thread(new run1).start; new thread(new run2).start; } //任务1 static class run1 implements runnable { @override public void run { //执行任务1 run1; //执行任务3 run3; } } //任务2 static class run2 implements runnable { @override public void run { //执行任务3 run3; //执行任务1 run1; //执行任务2 run2; } } //任务1 public static void run1 { system.out.println("run1->" + system.currenttimemillis); } //任务2 public static void run2 { system.out.println("run2->" + system.currenttimemillis); } //任务3 public static void run3 { system.out.println("run3->" + system.currenttimemillis); }
我把代码切换模式
public static void main(string[] args) throws interruptedexception { //线程并行情况,有多个线程执行多个任务/函数 long test1 = threadpool.addthreadmodel("测试线程-1"); long test2 = threadpool.addthreadmodel("测试线程-2"); //添加任务 threadpool.addtask(test1, new run1); threadpool.addtask(test2, new run2); //添加定时器任务 threadpool.addtimertask(test1, new timerrun1); threadpool.addtimertask(test2, new timerrun2); } //任务1 static class run1 extends taskevent { @override public void run { //执行任务1 run1; //执行任务3 run3; } } //任务1 static class timerrun1 extends timertaskevent { public timerrun1 { super(500);//500毫秒无限制执行 } @override public void run { //执行任务1 run1; //执行任务3 run3; } } //任务2 static class run2 extends taskevent { @override public void run { //执行任务3 run3; //执行任务1 run1; //执行任务2 run2; } } //任务2 static class timerrun2 extends timertaskevent { public timerrun2 { super(500);//500毫秒无限制执行 } @override public void run { //执行任务3 run3; //执行任务1 run1; //执行任务2 run2; } } //任务1 public static void run1 { system.out.println("run1->" + system.currenttimemillis); } //任务2 public static void run2 { system.out.println("run2->" + system.currenttimemillis); } //任务3 public static void run3 { system.out.println("run3->" + system.currenttimemillis); }
接下来我们看看执行效果
run1->1472120543013 run3->1472120543013 run3->1472120543017 run1->1472120543017 run2->1472120543017 run1->1472120543517 run3->1472120543517 run2->1472120543517 run1->1472120544018 run3->1472120544018 run2->1472120544018 run1->1472120544520 run3->1472120544520 run2->1472120544520 run1->1472120545021 run3->1472120545021 run2->1472120545021 run1->1472120545521 run3->1472120545521
一切正常;
这就是我的自定义线程模型;
到这里我的自定义线程模型就算介绍完成了;
那么优缺点在哪里呢?
优点是,数据流程控制很清晰,包括现在执行情况,以及线程卡死监控和任务 的定时器执行;
缺点,这个自定义线程模型依然不可能解决线程数据安全和临界区问题,在适当的时候依然需要靠锁或者其他形式来解决;
不足之处希望大神们指出,我好即时纠正。
上一篇: java获取昨天日期字符串的方法
推荐阅读