RunnableTrafficLightCtrlStatemachineWrapper.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 SCInterface
  21. */
  22. protected SCInterface sCInterface = new SynchronizedSCInterface() {
  23. public void raisePolice_interrupt() {
  24. eventQueue.add( new Runnable() {
  25. @Override
  26. public void run() {
  27. synchronized (statemachine) {
  28. statemachine.getSCInterface().raisePolice_interrupt();
  29. statemachine.runCycle();
  30. }
  31. }
  32. });
  33. }
  34. };
  35. public void timeElapsed(final int eventID) {
  36. eventQueue.add(new Runnable() {
  37. @Override
  38. public void run() {
  39. synchronized (statemachine) {
  40. statemachine.timeElapsed(eventID);
  41. statemachine.runCycle();
  42. }
  43. }
  44. });
  45. }
  46. /**
  47. * This method will start the main execution loop for the state machine.
  48. * First it will init and enter the state machine implicitly and then will
  49. * start processing events from the event queue until the thread is
  50. * interrupted.
  51. */
  52. @Override
  53. public void run() {
  54. boolean terminate = false;
  55. while(!(terminate || Thread.currentThread().isInterrupted())) {
  56. try {
  57. Runnable eventProcessor = eventQueue.take();
  58. eventProcessor.run();
  59. } catch (InterruptedException e) {
  60. terminate = true;
  61. }
  62. }
  63. }
  64. }