1: synchronized

1.1: Atomicity of operations within a block 1.2: visibility by 'before you can execute unlock, this variable must be synchronized back to main memory' 1.3: OrderCopy the code

2: Use of synchronized

1.1: Decorates the instance method 1.2: decorates the static method 1.3: decorates the S code block to lock the object in ynchronized parenthesesCopy the code

3: Implementation principle

1.1: The JVM implements method synchronization and code block synchronization based on entering and exiting Monitor objects. Method-level synchronization is implicit, that is, controlled without bytecode instructions, and is implemented in method calls and return operations. The JVM can distinguish whether a method is synchronized from the ACC_SYNCHRONIZED access flag in the method_info Structure in the method constant pool. When a method is invoked, the calling instruction checks to see if the method's ACC_SYNCHRONIZED access flag is set. If so, the thread of execution will hold monitor (a term used in the vm specification) before executing the method. Monitor is finally released when the method completes, either normally or abnormally. B. Code blocks are synchronized using the bytecode instructions monitorenter and Monitorexit. They are at the beginning and end of the synchronized code block, respectively. Each object has a monitor lock. The monitor is locked when it is occupied, and the thread attempts to acquire ownership of the Monitor when it executes the Monitorenter instruction as follows: 1. If the number of entries to monitor is 0, the thread enters monitor and sets the number of entries to 1. The thread is the owner of Monitor. 3. If another thread has occupied the monitor, the thread blocks until the number of entries is 0, and then attempts to acquire ownership of the monitor again.Copy the code

Derived from: We see https://blog.csdn.net/weixin_38481963/article/details/88384493 for synchronization method, resulting from the decompiled ACC_SYNCHRONIZED flag, Decompile synchronized code blocks to get monitorenter and Monitorexit directives.Copy the code