title: Problem with thread synchronizing in Java
body: <p>I'm well aware that this might be considered a duplicate, however I ran through many answers considering my problem here I can't come up with a solution.</p>
  
  <p>I synchronized my runnable with an object shared by multiple threads and explicitly synchronized the method I am using inside, but the outcome of the program is always 3000.</p>
  
  <p>I tried locking the <code>Counter</code> class but it won't change a thing.
  Could anyone explain me why none of my actions work in this particular example?</p>
  
  <pre class="lang-java prettyprint-override"><code>    public static void zad3() {
          var counter = new Counter();
  
          var toRun = new Runnable() {
              @Override
              public void run() {
                  synchronized (counter) {
                      for (var i = 0; i &lt; 1000; i++) {
                          counter.add(1);
                      }
                  }
              }
          };
  
          var t1 = new Thread(toRun);
          var t2 = new Thread(toRun);
          var t3 = new Thread(toRun);
  
          t1.start();
          t2.start();
          t3.start();
  
          try {
              t1.join();
              t2.join();
              t3.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
  
          System.out.println("counter = " + counter.getCount());
     }
  </code></pre>
  
  <pre class="lang-java prettyprint-override"><code>public class Counter {
      protected long count_ = 0;
  
      public synchronized void add(long value) {
          count_ += value;
      }
  
      public long getCount() {
          return count_;
      }
  }
  </code></pre>
  
  <p><strong>edit:</strong>
  As suggested the problem was in the loop being constantly ran a <code>1000</code> times by each of the threads.
  My solution:</p>
  
  <pre class="lang-java prettyprint-override"><code>        var toRun = new Runnable() {
              @Override
              public void run() {
                  synchronized (counter) {
                      for (var i = counter.getCount(); i &lt; 1000; i++) {
                          counter.add(1);
                      }
                  }
              }
          };
  </code></pre>