title: The output of the counter to this multi-threaded code
body: <p>I came across a Java problem about multi-threaded programming (please see the code below). Based on <a href="https://stackoverflow.com/questions/6498982/multithread-state-dependent-issue">this question</a> and answer on StackOverflow, I think I understand why there could be a deadlock. But what I don't understand was if the program works correctly (i.e. there is no deadlock), what would be the value of <code>foo</code> printed? I thought it would be 20 (thread1 counting up to 10 and thread2 counting up to 10 more). Could someone help me explain how this might (preferably in a simple way because I'm still new to thread programming)? Thank you.</p>
  
  <pre><code>public class ThreadTest{
  
    private static class ThreadOne extends Thread{
      private ThreadTwo threadTwo; 
      public int foo = 0;
  
      public void setThreadTwo(ThreadTwo th){
         threadTwo = th;
      }
  
      public void run(){
        try{
          for(int i=0;i&lt;10;i++) foo += i;
  
          synchronized(this){this.notify();};
  
          synchronized(threadTwo){threadTwo.wait();};
  
          System.out.print("Foo: " + threadTwo.foo);
        }catch(InterruptedException e){ e.printStackTrace();}    
      }
    }
  
    private static class ThreadTwo extends Thread{
  
      private final ThreadOne threadOne;
      public int foo = 0;
  
      public ThreadTwo(ThreadOne th){
        threadOne = th;
      }
  
      public void Run(){
         try{
           synchronized(threadOne){threadOne.wait();}
           foo = threadOne.foo;
  
           for(int i=0;i&lt;10;i++) foo += i;
           synchronized(this){this.notify();};
             }
         catch(InterruptedException e){e.printStackTrace();}    
      }    
    }
  
    public static void main(){
      ThreadOne th1 = new ThreadOne();
      ThreadTwo th2 = new ThreadTwo(th1);
  
      th1.setThreadTwo(th2);
  
      th1.start(); th2.start();
      th1.join(); th2.join();
    } 
  }
  </code></pre>