Multithreading (1): synchronized and volatile

synchronized: achieve synchronization

Lock mechanism

When compiled into bytecode, the monitorenter will be inserted at the entry position, and the monitorexit bytecode command will be inserted when exiting.

Built-in lock            

Every Java object can be used as a lock to achieve synchronization. These locks are called built-in locks. When a thread enters a synchronized code block or method, it will automatically acquire the lock, and when it exits a synchronized code block or method, the lock will be released. The only way to obtain a built-in lock is to enter the synchronized code block or method protected by this lock.        

Mutex            

The built-in lock is a mutual exclusion lock, which means that only one thread can acquire the lock. When thread A tries to acquire the built-in lock held by thread B, thread A must wait or block until thread B releases the lock. If thread B does not release the lock, thread A will wait forever.

  • Modification of ordinary methods: lock the instance of the object, new multiple instances, and then call the locked method for each instance without blocking.
  • Decorate static methods: lock the entire class
  • Modified code block: lock an object synchronized (lock) lock the lock object

 

 

Volatile: achieving visibility

Volatile modified variables, when the modified variable changes, the main memory will be updated immediately to make others visible.

Instruction reordering is forbidden: Instruction reordering: cpu will disrupt the writing order , you need to know more about mark

So volatile is suitable for one write and many read

Guess you like

Origin blog.csdn.net/qq_22420441/article/details/86499402