Synchronization method and synchronization block

Synchronization method

  • Since we can use the private keyword to ensure that the data object can only be accessed by the method, we only need to propose a mechanism for the method. This mechanism is the synchronized keyword, which includes two usages: synchronized method and synchronized block

    同步方法:public synchronized void methood(int args){
          
          }
    
  • The synchronized method controls access to the "object". Each object corresponds to a lock. Each synchronized method must acquire the lock of the object calling the method before it can be executed. Otherwise, the thread will block. Once the method is executed, the lock will be exclusively used until the The method returns to release the lock, and the blocked thread can obtain the lock and continue execution

    缺陷:若将一个打的方法申明为synchronized将会影响效率
    

Sync block

  • Synchronized block: synchronized (obj){}
  • obj is called a synchronization monitor
    • Obj can be any object, but it is recommended to use shared resources as a synchronization monitor
    • There is no need to point to the synchronization monitor in the synchronization method, because the synchronization monitor of the synchronization method is this, the object itself, or the class [explained in reflection]
  • The execution process of the synchronization monitor
    1. The first thread accesses, locks the synchronization monitor, and executes the code
    2. The second thread visited and found that the synchronization monitor was locked and could not be accessed
    3. The first thread access is complete, unlock the synchronization monitor
    4. The second thread visits and finds that the synchronization monitor is not locked. Locked and accessed

Guess you like

Origin blog.csdn.net/qq_45162683/article/details/111636106