简体   繁体   中英

Do synchronized methods have locks of their own?

Suppose I have

class myClass {

    synchronized methodA { };

    synchronized methodB { };
}

Does it mean that there are 2 implicit locks? One for methodA and one for B? I was reading Cracking the Coding Interview by Gayle McDowell, and she says that locking happens at the level of method + object, as opposed to object. I was under the impression that myClass simply has one lock and every synchronized method uses that. Can anyone explain ?

This

synchronized void methodA 
{
  //code
}

is equivalent to

void methodA 
{
  synchronized(this)
  {
    //code
  }

}

So, synchronized in front of a method will use the instance of the object itself as a lock.

Both of this methods used same lock. Every object in java has his internal mutex.

synchronized void method() {}

and

synchronized(this) {}

used same lock.

But if you try synchronized on static method - it will use different locks:

static synchronized method() { // used Class lock ! not object lock
} 

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