'Why does synchronized on the count itself do not work? [duplicate]

Why the synchronizing on the count does not make it safe?

class Increment implements Runnable{
    static Integer count = new Integer(0);

    public void run(){
        for (int i = 0; i< 1_000_000; i++){
            synchronized (count){
                count ++;
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {

        Thread one = new Thread(new Increment());
        Thread two = new Thread(new Increment());

        one.start();
        two.start();
        one.join();
        two.join();

        System.out.print(count);

    }
}

1555622

I know if I would put there some dummy object o like this

class Increment implements Runnable{
    static Integer count = new Integer(0);

    static Object o = new Object();
    public void run(){
        for (int i = 0; i< 1_000_000; i++){
            synchronized (o){
                count ++;
            }
        }    }

    public static void main(String[] args) throws InterruptedException {

        Thread one = new Thread(new Increment());
        Thread two = new Thread(new Increment());

        one.start();
        two.start();
        one.join();
        two.join();

        System.out.print(count);

    }
}

2000000

it would be safe. But I do not understand why it doesn't work on count itself



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source