title: Java: Multithreading accessing main thread variables/methods
body: <p>I was testing the following code, and I was wondering how come the threads could access the the increment method?</p>
  
  <p>I was thinking this since thread1 and thread2 are objects created from an anonymous class that don't inherit worker class how can they access the increment() method? what is the theory behind it?</p>
  
  <pre><code>public class Worker {
      private int count = 0;
  
      public synchronized void increment() {
          count++;
      }
  
      public void run() {
          Thread thread1 = new Thread(new Runnable() {
              public void run() {
                  for(int i = 0; i &lt; 10000; i++) {
                      increment();
                  }
              }
          });
          thread1.start();
  
          Thread thread2 = new Thread(new Runnable() {
              public void run() {
                  for(int i = 0; i &lt; 10000; i++) {
                      increment();
                  }
              }
          });
          thread2.start();
  
          try {
              thread1.join();
              thread2.join();
          } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
  
          System.out.println("Count is: " + count);
      }
  }
  </code></pre>