title: accessing shared variable from inside a Runnable class
body: <p>I need to define a shared variable in my Main class's main() method. I need two threads to be able to access that shared variable. Im creating the threads by implementing the Runnable interface and implementing the abstract run() method of the interface. How do i refer to the shared variable defined in the Main class's main() method from within the run() method defined in my class that implements the Runnable interface? Obviously just calling them by name is not working - as they appear out of my Runnable class's scope.</p>
  
  <p>EDIT - apologies, here is a simple example</p>
  
  <pre><code>public Class DoThread implements Runnable {
  
      public void run(){
          sharedVar += 1
      }
  
  
  }
  </code></pre>
  
  <p>and in a separate .class file:</p>
  
  <pre><code>public Class Main {
  
      public static void main(String[] args) {
          int sharedVar = 0;
  
          Thread t1 = new Thread(new DoThread());
          Thread t2 = new Thread(new DoThread());
  
          t1.start();
          t2.start();
  
          t1.join();
          t2.join();
  
      }
  
  
  }
  </code></pre>
  
  <p>so should i be creating an object to store the shared var in and then passing that object to both the DoThread() constructors when creating the threads? I get confused sometimes between when java passes by ref or passes by var, so if i do it this way, will changes to the shared var by t1 be seen by t2?</p>