title: Java Synchronized Method on Static Variable
body: <p>I'm doing a college class on Java concurrency and was recently given a simple task to create 5 threads numbered from 1 to 5, then get each thread to write its thread number to a static variable in the class using a synchronized static method.</p>
  
  <p>The solution I was given by the lecturer is below:</p>
  
  <pre><code>public class thread1 extends Thread {
  
  private int threadNumber;
  private static int threadCount = 0;
  private static int value;
  
  public thread1(){
        threadNumber = ++threadCount;
        System.out.println("Thread " + threadNumber + " is created" );
  }
  
  public synchronized static void setValue(int v){
        value = v;
        try{
             Thread.currentThread().sleep(100);
        }
             catch(InterruptedException e ){}
  
        System.out.println("the current value of the variable is " + value);
  }
  
  public void run() {
      setValue(threadNumber);
      return;
  }
  
  public static void main(String[] args) {
      for(int i = 0; i &lt; 5; i++){
          thread1 thr = new thread1();
          thr.start();
  }
  
  }
  }   
  </code></pre>
  
  <p>The output is supposed to be as follows:</p>
  
  <blockquote>
    <p>Thread 1 is created<br/> Thread 2 is created<br/> Thread 3 is
    created<br/> Thread 4 is created<br/> Thread 5 is created<br/> the
    current value of the variable is 1<br/> the current value of the
    variable is 2<br/> the current value of the variable is 3<br/> the
    current value of the variable is 4<br/> the current value of the
    variable is 5<br/></p>
  </blockquote>
  
  <p>But the output I am getting is below:</p>
  
  <blockquote>
    <p>Thread 1 is created<br/> Thread
    2 is created<br/> Thread 3 is created<br/> Thread 4 is created<br/>
    Thread 5 is created<br/> the current value of the variable is 1<br/>
    the current value of the variable is 5<br/> the current value of the
    variable is 4<br/> the current value of the variable is 3<br/> the
    current value of the variable is 2<br/></p>
  </blockquote>
  
  <p>The order of current value is obviously different each time.</p>
  
  <p>Is the solution I've been given incorrect? It's obviously not working in fulfilling its intended purpose which is to print out each of the thread's <b>value</b> variables in order. </p>
  
  <p>Could anyone shed some light on how I'd get it to print the thread numbers in order from 1 to 5 each time reliably? I thought the use of the synchronized <b>setValue</b> method would do the trick, but obviously not.</p>