0

I have written below mentioned code and i am expecting 12000 as an answer. however not getting correct answer. for every run i get some new number

package thread;

public class ThreadExp extends Thread {

    static volatile int count=0;

    public synchronized void increment() {
        count++;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ThreadExp a = new ThreadExp();
        a.start();
        ThreadExp a1 = new ThreadExp();
        a1.start();

        try {
            a.join();
            a1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(count);
    }

    public void run() {
        for(int i=1; i<=6000 ;i++) { 
            increment();
        }
    }
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 1
    Use an `AtomicInteger`. – Elliott Frisch Sep 16 '18 at 19:33
  • @ElliottFrisch, If this program worked the way the OP thought it would work, then the only thing it would ever do is print out the number 12000. Don't need `AtomicInteger` for that: All it needs is one line: `System.out.println("12000")`. But the OP's goal was not to make a program that prints `12000`, and it was not to make a program that counts to 12000. It was to learn what `synchronized` does and what it does not do. Obviously, that's still a work in progress. – Ohm's Lawman Sep 16 '18 at 20:45

1 Answers1

4

Non-static synchronized methods synchronize on the this object (see JLS, §8.4.3.6). Thus, the two instances of ThreadExp you use are not executing increment() mutually-exclusive.

You could fix your problem by defining increment() as static, since static methods synchronize on the class-Object representing the type.

Another solution was mentioned by Elliott Frisch: use AtomicInteger instead of the volatile int.

Turing85
  • 18,217
  • 7
  • 33
  • 58