The longest-used keyword in Java concurrency programming is synchronized
to explain the usage of this keyword and the confusing place.
synchronized
Keywords related to the concept of lock, in Java, synchronized lock Everyone is also popularly known as: Method Lock, Object lock and class lock three kinds.
Come to the conclusion first!
1 Both the adornment method and the adornment code block are object locks , and when a thread accesses a band synchronized
method, all the added methods cannot be accessed due to the existence of the object lock synchronized
(provided that the number of threads is called Methods in the same object instance )
2 It is a class lock Whether you modify a static method or lock an object . A class where static methods and static variables are only loaded and initialized in memory, so once a static method is declared synchronized
, All instantiated objects of this class share the same lock, called a class lock, when the method is called.
1 How to: Modify an object lock:
synchronized
Modifies the normal method, which locks the current object. Only one thread can enter a method of the same object instance at a time method()
.
The wording is as follows:
2 The object lock is written in two: decorated code block, lock
Instance Object
3 Type of Lock: modifying static methods
Class 4 Lock type two: modifier code block, lock
Class Object
In fact, the effect of the class lock modification method and the code block is the same as the object lock, because the class lock is only an abstraction concept, just to distinguish the characteristics of the static method, because the static method is common to all object instances, so the static method corresponding to the synchronized modified lock is also unique, So abstract out a class lock.
5 synchronized simultaneous modification of both static and non-static methods
The above synchronized
also modifies the static method and the instance method, the result alternately runs, proves that the class lock and the object lock are two different locks, the control different area, does not interfere.
Tips:
1. synchronized
keywords cannot be inherited. That is, subclasses override synchronized
methods that are decorated in the parent class, and the subclasses ' methods are still not synchronized.
2. When defining an interface method, you cannot use synchronized
keywords.
3. Construction methods cannot use synchronized
keywords, but you can use synchronized
code blocks.