1.synchronized can be used to modify a common method, or code block, this time synchronized lock is the current object, as long as there is a thread in the corresponding method or block of code, other threads must wait.
2.synchronized is valid only for modified methods, and other non-synchronized methods that lock the object are accessible.
3.synchronized can also be used to lock the specified object, and when a thread accesses the specified object, other threads attempting to access the specified object will block until the thread accesses the specified object end
4.synchronized can be used to modify a static method, the static method belongs to the class but not the object. Similarly, synchronized-modified static methods lock all objects of this class
The 5.synchronized (*.class) effect is the same as locking a static method, all objects that lock the class.
Summarize
A. Regardless of whether the Synchronized keyword is added to a method or an object, if the object it is acting on is non-static, the lock it obtains is an object, and if the synchronized object is a static method or a class, the lock it obtains is the same lock on the class, all objects of that class.
B. Each object has only one lock (lock) associated with it, and whoever gets the lock can run the code it controls.
C. Achieving synchronization is a costly overhead, and may even result in deadlocks, so avoid unnecessary synchronization controls as much as possible.
retouch Content |
Lock Type |
Example |
modifying code blocks |
Arbitrary object Lock |
Example Four |
Modifying a common method |
This lock |
Example Five |
modifying static methods |
Class lock |
Example Six |
The synchronized of the Java keyword