昨天在开发前置的时候,出现了这样的一个问题,当主服务一启动就会出现cpu100%的情况,修改之前的代码如下:
public class MsgHandleThread extends Thread {
private static Log log = LogFactory.getLog(MsgHandleThread.class);
public void run() { while (true) { MessageSyncQueue msgQueue = QueueManager.getMsgQueue(); if (msgQueue == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } TaskBean taskBean = msgQueue.pop(); if (taskBean != null) { int taskBeanStatus = taskBean.getBeanStatus(); log.info("[" + taskBean.getRequestBean().getWebStreamid() + "]进入循环线程,status=[" + taskBeanStatus +"]"); switch (taskBeanStatus) { //0:初始状态、调用过滤线程进行预处理 case Global.STATUS_0: new RequestFiltrateThread(taskBean).start(); break; //1:经过预处理、需要调用实际处理线程进行处理 case Global.STATUS_1: new CoreProcessThread(taskBean).start(); break; //2:经过处理后需要返回的任务 case Global.STATUS_2: new ResponseHandleThread(taskBean).start(); break; } } } } }
修改之后的代码为:
public class MsgHandleThread extends Thread {
private static Log log = LogFactory.getLog(MsgHandleThread.class);
private static MessageSyncQueue msgQueue = QueueManager.getMsgQueue(); public void run() { while (true) { if (msgQueue == null) { log.info("msgQueue初始化为空"); break; } TaskBean taskBean = msgQueue.pop(); if (taskBean != null) { int taskBeanStatus = Integer.parseInt(taskBean.getBeanStatus()); log.info("[" + taskBean.getRequestBean().getWebStreamid() + "]进入循环线程,status=[" + taskBeanStatus +"]"); switch (taskBeanStatus) { //0:初始状态、调用过滤线程进行预处理 case Global.STATUS_0: new RequestFiltrateThread(taskBean).start(); break; //1:经过预处理、需要调用实际处理线程进行处理 case Global.STATUS_1: new CoreProcessThread(taskBean).start(); break; //2:经过处理后需要返回的任务 case Global.STATUS_2: new ResponseHandleThread(taskBean).start(); break; } } try { Thread.sleep(Long.parseLong(PropertiesContext.instance.getMsgqueue_scan_interval())); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }最开始队列为空,却一直在读,就会进入死循环,需要过一段时间再去读,等到有元素之后再去读。