首页 新闻 赞助 找找看

怎么优化线程的run方法

0
悬赏园豆:20 [待解决问题]

该线程占用cpu时间长,并且占用内存多。run方法哪地方需要优化,请大侠们指教,坐等回答...  

 

下面是线程的run方法,该方法的作用是检查数据库中有没有未处理的事件,如果有,就处理。  

    while条件一直是true  

    commonService.basicQuery()方法是来查询数据库  

    catch中的doPauseThread()方法是让该线程睡5秒 

public void run() {
        String err = "Error occurred in FlightEventThread, Administrated";
        while (isThreadAlive) {
            try {
                List<FlightEvent> allEvent = commonService.basicQuery(
                        FlightEvent.class, (Object) exampleEvent, true,
                        "eventId");
                for (FlightEvent event : allEvent) {
                    event.setIsProcessed("P");
                    commonService.basicUpdate(event);
                    IEventProcessor eventProcessor = (IEventProcessor) Global.applicationContext
                            .getBean(event.getEventProcess().getProcessBean());
                    eventProcessor.setEvent(event);
                    try {
                        eventProcessor.execute();
                        eventProcessor.doSendMessageToFront();
                    } catch (IllegalDataException ie) {
                        log.error(err, ie);
                    } catch (Exception e) {
                        log.error(err, e);
                    }
                }
                /* Sleep is not needed disable by hwlcsx  */
                /*doPauseThread();*/
            } catch (Exception e) {
                log.error(err, e);
            }
            finally{
                doPauseThread();
            }
        }
    }
代俊建的主页 代俊建 | 初学一级 | 园豆:128
提问于:2012-12-21 15:43
< >
分享
所有回答(4)
0

通过注释掉,运行,看内存,找到最有影响的代码,再处理。

路过秋天 | 园豆:4787 (老鸟四级) | 2012-12-21 15:55
0

这个代码写的不太好,因为你在循环里面执行了 commonService.basicUpdate(event);

你应该考虑优化的你的处理逻辑。

Launcher | 园豆:45045 (高人七级) | 2012-12-21 16:02
0

如果是这段代码影响性能了,显然是对数据库的操作的问题。

1、看看commonService.basicQuery查询方法怎么实现的,不合理的查询会很慢;

2、不应该一条一条的执行commonService.basicUpdate

至于内存太大,看看是不是每次查询的时候生成的对象太多了,因为你的while条件一直是true,就会一直生成。。。

iBoyer | 园豆:196 (初学一级) | 2012-12-21 17:59
0

占用内存多,是你包装run方法的那个类的成员变量太多或者是线程中你不断地在新建对象。如果是占用cpu多,就让它sleep吧。

angelshelter | 园豆:9887 (大侠五级) | 2012-12-21 18:32
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册