title: java multi threading traffic signal example
body: <p>I am trying to implement traffic signal in java using multi threading concepts. I want to use synchronization. This is code i have written but it doesn't run according to my expectations :P .. What i am actually doing is taking a variable "a" whose value determines which light should be on at a particular time. For eg: a==0 should give red light.. then red light acquires a lock on "a" and changes the value to a==1 after some interval and then switches on to orange light and the same happens for green light as well .. </p>
  
  <p>Code:</p>
  
  <pre><code>    package test;
  
  class Lights implements Runnable {
  
      int a=0,i,j=25;
      synchronized public void valueA()
      {
          a=a+1;
      }
  
      public void showLight()
      {
          System.out.println("The Light is "+ Thread.currentThread().getName());
      }
      @Override
      public void run() {
          // TODO Auto-generated method stub
              for(i=25;i&gt;=0;i--)
              {
                  while(j&lt;=i&amp;&amp;j&gt;=10&amp;&amp;a==0)
                  {
                  showLight();
              /*some code here that locks the value of "a" for thread 1   
                  and keeps it until thread 1 unlocks it! */
                  try {
  
                      Thread.sleep(1000);
  
  
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
                  j--;
                  }
  
  
              while(j&lt;10&amp;&amp;j&gt;=5&amp;&amp;a==1)
              {
  
                  showLight();
                  /*some code here that locks the value of "a" for thread 1   
                  and keeps it until thread 1 unlocks it! */
                  try {
                      Thread.sleep(500);
  
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
                  j--;
              }
  
  
              while(j&lt;5&amp;&amp;j&gt;=0&amp;&amp;a==2)
              {
                  showLight();
              try {
                  Thread.sleep(500);
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
  
          }
              }
      }
  }
  </code></pre>
  
  <p>Main Class:</p>
  
  <pre><code>package test;
  
  public class MainTraffic {
  public static void main(String args[])
  {
      Runnable lights=new Lights();
  
      Thread one=new Thread(lights);
      Thread two=new Thread(lights);
      Thread three=new Thread(lights);
  
      one.setName("red");
      two.setName("orange");
      three.setName("green");
  
      one.start();
      two.start();
      three.start();
  
  
  }
  }
  </code></pre>