Question about Java synchronized

2019-01-14 04:06发布

The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave". What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process(). We have several instances of Worker running in their own threads. We want to prevent more than one instance running the process() method simultaneously. Will synchronized do this?

Thanks.

7条回答
做个烂人
2楼-- · 2019-01-14 04:38

Only one thread can hold a lock on an object at any one time.

A synchronized method attempt to hold a lock on the instance. Another thread can also hold a lock on another instance of the same class. Another thread cannot enter another synchronized method of the same instance. i.e. it is not the method which is locked.

However a thread can enter a non-synchronized method while another thread holds a lock on that object. Only synchronized methods are protected.

A static synchronized method obtains a lock on the Class rather than the object. However, the follows the same rules as non-static method except with a different object.

Note: There is no "instance" for static method even though you can write code which appears to use an instance. e.g. instance.staticMethod()

查看更多
登录 后发表回答