I'm trying to understand concurrency in java. I know about synchronized, that it creates a monitor on object, and after that another Threads can't do operations with this object. Volatile - is about processor cache, and if i use it, all threads don't create a copy of object. So, in my mind if i run this code, i will get the correct counter value (40000). But i get incorrect!
public class Main {
private static volatile Integer counter = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Counter();
Thread thread2 = new Counter();
thread.start();
thread2.start();
thread.join();
thread2.join();
System.out.println(counter);
}
public static class Counter extends Thread{
@Override
public void run() {
for (int i = 0; i < 20000; i++) {
synchronized (counter){
counter++;
}
}
}
}
}
But if i use syncronized method, i will get correct result:
public class Main {
private static volatile Integer counter = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Counter();
Thread thread2 = new Counter();
thread.start();
thread2.start();
thread.join();
thread2.join();
System.out.println(counter);
}
public synchronized static void increment(){
counter++;
}
public static class Counter extends Thread{
@Override
public void run() {
for (int i = 0; i < 20000; i++) {
increment();
}
}
}
}
So question - why synchronized doesn't work on Integer object??