How Synchronization works in Java?

后端 未结 8 594
广开言路
广开言路 2020-12-08 21:46

I have a doubt regarding Java Synchronization . I want to know if I have three Synchronized methods in my class and a thread acquires lock in one synchronized method other t

8条回答
  •  我在风中等你
    2020-12-08 22:10

    Synchronization in java is done through aquiering the monitor on some specific Object. Therefore, if you do this:

    class TestClass {
        SomeClass someVariable;
    
        public void myMethod () {
            synchronized (someVariable) {
                ...
            }
        }
    
        public void myOtherMethod() {
            synchronized (someVariable) {
                ...
            }
        }
    }
    

    Then those two blocks will be protected by execution of 2 different threads at any time while someVariable is not modified. Basically, it's said that those two blocks are synchronized against the variable someVariable.

    When you put synchronized on the method, it basically means the same as synchronized (this), that is, a synchronization on the object this method is executed on.

    That is:

    public synchronized void myMethod() {
        ...
    }
    

    Means the same as:

    public void myMethod() {
        synchronized (this) {
           ...
        }
    }
    

    Therefore, to answer your question - yes, threads won't be able to simultaneously call those methods in different threads, as they are both holding a reference to the same monitor, the monitor of this object.

提交回复
热议问题