Synchronized method does not work as expected

后端 未结 5 1591
广开言路
广开言路 2020-12-18 09:26

I have a variable which is shared by two threads. The two threads will do some operations on it. I don\'t know why the result of sharedVar is different every time I execute

5条回答
  •  猫巷女王i
    2020-12-18 10:05

    A synchronized method protects the resource this that means that your code is equivalent to:

    private void addOne()
    {
        synchronized(this)
        {
            for (int i = 0; i < times; ++i)
            {
                Main.sharedVar ++;
            }
        }
    }
    

    But you have 2 objects for which addOne method is called. That means this for mt1.addOne is not the same than this for mt2.addOne and therefore you don't have a common resource of synchronization.

    Try changing yout addOne code to:

    private void addOne()
    {
        synchronized(MyThread.class)
        {
            for (int i = 0; i < times; ++i)
            {
                Main.sharedVar ++;
            }
        }
    }
    

    And you will observe the expected behaviour. As the comments below suggest, it is better to use a different object than MyThread.class for synchronization since class objects are accesible from many points and it is easy that other code may try to synchronize using the same object.

提交回复
热议问题