views:

187

answers:

3

Is there a way of Holding a thread in a State waiting for changes? I mean wait tll something happend (change var, call method, etc..) perhaps it needs using Event Listeners, or synchronized objects/methods..

The usual aproach for statemachines like this

statemachine example

That uses a do{..}while(true) loop that could work for singled threaded(and no GUI) application but it CANT'T be used with threads.. (at least you want to use a core for every threaded state machine)

So to avoid that processor consuming task a simple (and ugly) way is a "periodic checker", I mean adding a Sleep other idea is defining a synchronized object and using wait instead of thread Sleep

example:

                do{

                    Switch(state)
                    {

                       case STATE_A:
                         //..A things                         
                       break;

                       case STATE_B:
                          //..B things                         
                       break;

                       ...

                       case STATE_Z:
                          //..Z things                         
                       break;

                     }


// Here!  =>           wait()?  Thread.sleep(TIME_CONST)? //Hold and yield


                 }while(powerOn);

The drawback is adding complexity using synchronized or that anything that happen within TIME_CONST would be invisible

I would like to know other ideas for doing this, thanks !

+4  A: 

Yes, you would be using wait/notify. That is what it is for.

Or maybe your state machine does not need to have its own thread. Other threads could call an update method on the state machine when something interesting happens.

Thilo
I see it, that I thought was complex, is the simplest way!, thanks
Hernán Eche
A: 

You can also use Lock and Condition (Java 1.5+). It's like wait/notify and there is an example in the javadoc

ecerulm
I'll check it, thank you
Hernán Eche
+1  A: 

Try using a Pipe between the event source thread and the FSM embodiment thread. This is sufficient for a 2 threaded implementation.