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++;
}
}```