one, how many chestnuts??
1. When two concurrent threads access the synchronized (this) synchronization code block in the same object, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.
2. When a thread accesses one synchronized (this) of object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.
3. When a thread accesses one of the synchronized (this) synchronization blocks of object, other threads will block access to all other sychronized (this) synchronous blocks of code in object.
4. A third example can also be implemented using the Synchronized method. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object. (The Synchronized keyword for method m4t2xx can be in public or before public)
Ii. Overview
Synchronized is for a critical section, the so-called critical section refers to access to this place at most only one thread inside (like a pen can be used by multiple people, but only one person at a time). Synchronized can do this by locking the object into the critical section to achieve the purpose of serial access to the critical section, and the scope of the object itself will determine the granularity of the lock.
-
Normal method before adding synchronized:
Synchronized public void Test () {...}
This action is equivalent to wrapping a synchronized (this) before and after the method body, or adding a lock object to the object where the current class resides.
-
static method before adding synchronized:
Synchronized public static void Test () {...}
This lock operation is equivalent to locking the class object of the current classes, such as this class is called a, which is equivalent to performing a synchronized (a.class) operation.
Synchronized is mainly in these two ways, the rest of the operation is based on this derived from. For example, "code block plus lock":
Locking is not actually a block of code, but an object, so mutual exclusion occurs when synchronized (object) occurs in other code.
In fact, synchronized (this) is also derived in this way, just before the method of adding synchronized with a difference, that is, its granularity is not at the method level, but at a specified code block level.
The operation of multiple threads within a critical section is definitely serial, which is guaranteed by Java.
However, the cost of synchronized is also very large.
Sychronized methods in Java differ from sychronized blocks