When synchronized lock code block in Java, does this class need to be a singleton?
高洛峰
高洛峰 2017-06-28 09:22:12
0
2
943

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?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
Ty80

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.

扔个三星炸死你

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template