search

Home  >  Q&A  >  body text

java - synchronized在修饰代码块的时候,括号后面要跟什么啊?

ringa_leeringa_lee2767 days ago913

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-18 09:31:32

    synchronized (lock-object) {
    }

    The brackets should be followed by an object, which acts as a lock.
    synchronized(""), here you treat an empty string as a lock, and therefore think that you did not specify which object to lock.
    In fact, the empty string itself is an object. Moreover, if you have two instances and feed them the empty string, the two instances actually hold the same object.

    1. In Java, everything is an object, and the empty string is also an object.

    2. Constant strings, such as empty strings, are placed in the constant pool. The empty strings referenced by two instances are actually the empty strings in the constant pool and are the same object.

    reply
    0
  • Cancelreply