Question about Java synchronized

后端 未结 7 1571
小蘑菇
小蘑菇 2020-12-01 06:53

The Java documentation says that \"it is not possible for two invocations of synchronized methods on the same object to interleave\". What I need to know is whether synchro

7条回答
  •  难免孤独
    2020-12-01 07:23

    No, synchronized will not do this. More specifically synchronized on the instance level will not do this. Instead you will have to synchronize on the class level.

    For example instead of having:

    public synchronized method()
    {
        //do stuff
    }
    

    You will have to code as:

    public void method()
    {
        synchronized(this.getClass())
        {
            //do stuff
        }
    }
    

提交回复
热议问题