synchronized principle underlying implementation

When the thread to acquire the lock, which is a pointer to the starting address of a monitor object (implemented by the C ++) are. Each object instance will have a monitor. Where the monitor can be created together with the object, destroyed; or also automatically generated when a thread tries to acquire the object lock. The monitor is a unique after adding Synchronized keyword. synchronized sync blocks use monitorenter and monitorexit instructions to synchronize these two commands are essentially object to a monitor (monitor) were acquired, this process is exclusive, which means that only one thread at a time acquisition synchronized to the protected object's monitor. When the thread execution to monitorenter instruction, will try to get the object corresponding to monitor ownership, that is try to get the object's lock, and the implementation of monitorexit, is the release of monitor ownership.

There are three ways to lock synchronized, respectively,

  • Examples of modified method, the current applied to the locking instance, before entering a synchronization code to obtain the current instance of the lock
  • Static method, the lock acting on the current class objects, the synchronization code before entering the class object to obtain the current lock
  • Modifying the code block, designated lock object, to lock a given object, before entering the synchronization code library to obtain a given lock of the object.

Guess you like

Origin www.cnblogs.com/liuqing576598117/p/11519286.html