RunnableTrafficLightCtrlStatemachineWrapper.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package traffic.light.trafficlightctrl;
  2. import java.util.concurrent.BlockingQueue;
  3. import java.util.concurrent.LinkedBlockingQueue;
  4. /**
  5. * Runnable wrapper of TrafficLightCtrlStatemachine. This wrapper provides a
  6. * thread-safe, runnable instance of the state machine. The wrapper implements
  7. * the {@link Runnable} interface and can be started in a thread by the client
  8. * code. The run method then starts the main event processing loop for this
  9. * state machine.
  10. *
  11. * Please report bugs and issues...
  12. */
  13. public class RunnableTrafficLightCtrlStatemachineWrapper extends SynchronizedTrafficLightCtrlStatemachine implements Runnable {
  14. /**
  15. * The events are queued using a blocking queue without capacity
  16. * restriction. This queue holds Runnable instances that process the events.
  17. */
  18. protected BlockingQueue<Runnable> eventQueue = new LinkedBlockingQueue<Runnable>();
  19. /**
  20. * Interface object for SCITrafficLight
  21. */
  22. protected SCITrafficLight sCITrafficLight = new SynchronizedSCITrafficLight() {
  23. };
  24. /**
  25. * Interface object for SCInterface
  26. */
  27. protected SCInterface sCInterface = new SynchronizedSCInterface() {
  28. };
  29. public void timeElapsed(final int eventID) {
  30. eventQueue.add(new Runnable() {
  31. @Override
  32. public void run() {
  33. synchronized (statemachine) {
  34. statemachine.timeElapsed(eventID);
  35. statemachine.runCycle();
  36. }
  37. }
  38. });
  39. }
  40. /**
  41. * This method will start the main execution loop for the state machine.
  42. * First it will init and enter the state machine implicitly and then will
  43. * start processing events from the event queue until the thread is
  44. * interrupted.
  45. */
  46. @Override
  47. public void run() {
  48. boolean terminate = false;
  49. while(!(terminate || Thread.currentThread().isInterrupted())) {
  50. try {
  51. Runnable eventProcessor = eventQueue.take();
  52. eventProcessor.run();
  53. } catch (InterruptedException e) {
  54. terminate = true;
  55. }
  56. }
  57. }
  58. }