简体   繁体   中英

Synchronze on method call Java

I have a question about a block of code I am trying to understand

synchronized(Name.getname())
{
   Name.getname().add(this);
}

What does this block of code synchronize on? does it synchronize on the method call result or something else.

Yes it is synchronized. You used Name.getname() as a lock object. If one thread acquires the Name.getname() object then other thread will wait until releasing object

It synchronizes on the object returned by Name.getname() .

Just like System.out.println(Name.getname()) prints the value returned by Name.getname() .

Everywhere you use an Object, an expression of type Object can be used.

Name实例中的getname()返回的(引用)值(或静态方法,如果不是实例)用作锁定对象。

I'm not adding any information that you can't find in the other answers, but sometimes a picture helps.

I'm guessing that Name.getName() returns a reference to a singleton Name instance. If that's true, then your example is equivalent to this:

Name n = Name.getName();
synchronized(n) {
    n.add(this);
}

It seems strange to me that something called "Name" would be a singleton, and it seems strange to me that you would be allowed to add this to something called "Name", but I can't make any sense of your example at all unless Name.getName() always returns the same object reference.

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