Java – Threaded State Machines in Java

javamultithreadingstate-machineswitch statementsynchronized

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 !

Best Answer

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.