0

I am learning synchronization in Java and I cant find out why I cant get 24000 as a result for "c.count". When I run the code I get 23674, 23853, etc. Do you have any idea why?

public class Counter {
    public int count = 0;

    public static void main(String[] args) throws InterruptedException {
        
        Counter c = new Counter();
        
        ThreadT t1 = new ThreadT(c);
        ThreadT t2 = new ThreadT(c);        
        
        t1.start();
        t2.start();
        
        t1.join();
        t2.join();
        System.out.println(c.count);

    }
}

class ThreadT extends Thread {
    Counter c;

    ThreadT(Counter c) {
        this.c = c;
    }
    public void run() {
        for (int i = 0; i < 12000; i++) {
            add();
        }
    }

    synchronized void  add() {
    c.count++;
    }
}```
gerg
  • 19
  • 1
  • 6

1 Answers1

2

Notice that t1 calls add on the t1 object while t2 calls add on the t2 object. While add is synchronized, t1 and t2 are two different objects, so the two threads are not synchronizing with each other.

Each thread calls a synchronized method on its own thread object, so it synchronizes only with itself. You need both threads to call synchronized methods on the same object.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278