title: Core Java , Shared Counter in Multithreading env
body: <p>I got the java counter problem: two threads share a common counter and increment it in turns. Now can someone please show code examples of it using synchronization, Locks and AtomicIntegers means using different approach. I am not getting any good working code comparison for this problem. Thanks.</p>
  
  <pre><code>public class ThreadsExample implements Runnable {
      static AtomicInteger counter = new AtomicInteger(1);
  
      public ThreadsExample() {
      }
  
      static void incrementCounter() {
          System.out.println(Thread.currentThread().getName() + ": "
                  + counter.getAndIncrement());
      }
  
      @Override
      public void run() {
          while (counter.get() &lt; 1000) {
              incrementCounter();
          }
      }
  
      public static void main(String[] args) {
          ThreadsExample te = new ThreadsExample();
          Thread thread1 = new Thread(te);
          Thread thread2 = new Thread(te);
          thread1.start();
          thread2.start();
      }
  }
  </code></pre>