title: Threads in inner class
body: <p>This code has no inner classes:</p>
  
  <pre><code>class Threads1 implements Runnable { 
  
      int x = 0; 
  
      public void run(){ 
          int current = 0; 
          for(int i = 0; i&lt;4; i++){  
              current = x; 
              System.out.println(current + ", ");
              x = current + 2; 
          }  
      }  
  } 
  
  public class b{ 
  
      public static void main(String[] args) {
          Runnable r1 = new Threads1();
          new Thread(r1).start(); 
          new Thread(r1).start(); 
      } 
  }
  </code></pre>
  
  <p>OUTPUT : </p>
  
  <pre><code>0, 2, 0, 4, 6, 2, 4, 6
  </code></pre>
  
  <p>This code uses an inner class called "Runner":</p>
  
  <pre><code>public class Threads1 { 
      int x = 0; 
      public class Runner implements Runnable {
          public void run(){  
              int current = 0; 
              for(int i = 0; i&lt;4;i++){ 
                  current = x;  
                  System.out.println(current + ", "); 
                  x = current + 2;  
              }
          }
      }
  
      public static void main(String[] args) {  
          new Threads1().go();
      }
  
      public void go(){
          Runnable r1 = new Runner();
          new Thread(r1).start();
          new Thread(r1).start();
      }
  }
  </code></pre>
  
  <p>OUTPUT :  (0, 2, 4, 4, 6, 8, 10, 6,) or (0, 2, 4, 6, 8, 10, 12, 14,)</p>
  
  <p>I learned that when two threads are created , they work on their own stacks, which means they share nothing with each other i.e output ( 0, 2, 0, 4, 6, 2, 4, 6) might be from ( T1, T1, T2, T1, T1 ,T2, T2, T2) where T1 AND T2 are Thread 1 and Thread 2.</p>
  
  <p>However , when I used <code>run()</code> in the inner class, both threads share the <code>Current</code> variable with each other. For example output  (0, 2, 4, 4, 6, 8, 10, 6,) might be from (T1 ,T1, T1 ,T2 ,T2, T2, T2, T1). As you can see, there is double a 4 in the output which means thread1 handed over its value to thread2. Why is that so?</p>