I'm trying to get a small program to demonstrate synchronization but for whatever reason, it's not fulfilling my expectations. The point is to make 1000 threads and have them all add 1 to the static Integer object "sum". The output is supposed to be 1000 but I getting different outputs. It's like the addSum() method isn't synchronized at all. I've tried delaying the println, thinking it was printing sum too quickly but that's not the problem. What am I missing here?
public class sumsync implements Runnable {
public static Integer sum = new Integer(0);
public sumsync(){
}
private synchronized void addSum(int i){
sum += i;
}
@Override
public void run() {
addSum(1);
}
}
Main class:
public class sumsyncinit {
private static final int max_threads = 1000;
public static void main(String[] args) {
sumsync task = new sumsync();
Thread thread;
for(int i=0; i<max_threads;i++){
thread = new Thread(task);
thread.start();
}
System.out.println(sumsync.sum);
}
}