Home  >  Q&A  >  body text

When synchronized lock code block in Java, does this class need to be a singleton?

When it locks a method or a code block, at most one thread can execute this code at the same time. When two concurrent threads access this locked synchronization code block in the same object object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing this code block before it can execute this code block.

The question is, if two threads access different instances of this object, will they still be blocked?

高洛峰高洛峰2669 days ago906

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-28 09:24:12

    synchronized can be used in the following three ways

    1. Specify the object to lock. Similar to synchronized (instance) {}.

    2. Acts directly on instance methods. It is equivalent to locking the current instance. Before entering the synchronization method, you must obtain the lock of the current instance.

    3. Acts directly on static methods. It is equivalent to locking the current class and obtaining the lock of the current class before entering the synchronization method.

    For the above 1 and 2. The thread must be blocked only if it is the same object or the same instance.

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-28 09:24:12

    Locks are added to object instances. Locks added to different objects will not affect each other. Two threads accessing two different objects will not block each other.

    reply
    0
  • Cancelreply