The use of synchronized

analyze:

Several uses of synchronized:

Object lock -- lock on an instance object. If the class is a singleton, then the lock also has the concept of a global lock.

               The instance lock corresponds to the synchronized keyword.

Modified code block synchronied { } synchronied(this) { } or synchronied(object) { }

Modified member method public synchronized void method(){}

Class lock -- the lock is for the class, and the threads share the lock no matter how many objects there are.

The corresponding global lock is static synchronized (or locked on the class or classloader object of the class).

    public static synchronized void method(){} //Note that this is actually the class object of this class

    public static synchronized(类.class) void method(){}

Features:

1) The synchronized keyword cannot be inherited.
Although synchronized can be used to define methods, synchronized is not part of the method definition, so the synchronized keyword cannot be inherited.

If a method in the parent class uses the synchronized keyword and the method is overridden in the subclass, the method in the subclass is not synchronized by default, and must be explicitly specified in the subclass's The synchronized keyword can be added to the method. Of course, you can also call the corresponding method in the parent class in the subclass method, so although the method in the subclass is not synchronized, the subclass calls the synchronization method of the parent class, so the method of the subclass is equivalent to synchronization .

2) The synchronized lock has the characteristics of reentrancy and satisfies the unfair mechanism




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325894151&siteId=291194637