简体   繁体   中英

how the synchronized keyword lock the method or block using the object

When we want to lock the block by synchronized statements we pass a object to it, I want to know that how this object lock the block, actually I want to know the mechanism of lock by synchronized keyword.

example:

Object object = new Object();
synchronized (object) {
    //do something
} 

my question is how object lock the block.

When a thread encounters a synchronized block (which uses objects for synchronization, as in your example) the following happens:

  1. the Java runtime checks if an other thread has already started executing the synchronized block (and is not finished yet) with the same "blocking" object instance

  2. If yes: our thread must wait (it is blocked) until the other thread finishes. After the other thread releases the lock (and no other waiting thread acquires the lock before out thread), ours can enter the block

  3. If no: our thread can immediately enter the synchronized block

The same instance is a very important part, consider the following example:

public void method() {
    Object object = new Object();
    synchronized (object) {
        //do something
    } 
}

In this example synchronization will effectively never happen, threads will never block. Because each thread creates a new instance before encountering the block. They never use the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM