I wrote a SharedObject class which has two methods to increment a variable. The expected result is 200000 but it shows much less than that. I thought the synchronized block will acquire lock on the cnt variable and thus no two threads can modify or access it but it's not happening. Why is it so?
public class Main {
public static void main(String[] args) throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread producer = new Thread(new Runnable() {
@Override
public void run() {
sharedObject.produce();
}
});
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
sharedObject.consume();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println(sharedObject.cnt);
}
static class SharedObject {
Integer cnt = 0;
void produce() {
for(int i=0; i<100000; i++) {
synchronized (cnt) {
cnt++;
}
}
}
void consume() {
for(int i=0; i<100000; i++) {
synchronized (cnt) {
cnt++;
}
}
}
}
}