多次执行实时消息处理

时间:2013-07-05 17:56:53

标签: java multithreading

我已经在实时发送的消息上实现了一个线程池执行器。

以下是一些相关的示例代码:

class MessageProcessor implements SomeListener{
     StateInfo stateInfo;
     ExecutorService pool;
     MessageProcessor(StateInfo stateInfo) {
       pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
       this.stateInfo = stateInfo;
     }
     @Override
     void processMessage(final String messageComesInRealTime) {
         Runnable runner = new Runnable() {
           public void run() {
             if(!stateInfo.in_state) {
                 if(stateInfo.state == 1) {
                   stateInfo.in_state = true;
                   //do something with message
                   stateInfo.state = 2;
                 }
                 else if(stateInfo.state == 2) {
                  stateInfo.in_state = true;
                   //do something with message
                   stateInfo.state = 3;
                 }
                 //etc...
              }
         } 
       };
       pool.execute(runner);
       //etc...
    }
}

在processMessage方法中,消息以高速率实时传输,同时处理多条消息。但是当stateInfo.state变为true时,我不希望以相同的方式评估其他消息进程。在这种情况下,完全删除线程是否更好?或者可以在保持线程执行的同时绕过这种行为?感谢您的回复。

1 个答案:

答案 0 :(得分:0)

根据您的评论,听起来您需要将访问和分配同步到您的in_state变量。

你可以这样做:

private final Object lock = new Object();
//...
public void run(){
    boolean inState = false;
    synchronized(lock){
        inState = inState();
        if(inState){ setInState(false);}
    }
}
boolean inState(){
        return this.stateInfo.in_state;
}
void setInState(boolean value){
    this.stateInfo.in_state=value;
}

还要确保将StateInfo中的in_state变量声明为volatile。