About synchronization method and a synchronization code blocks

About synchronization method and a synchronization code blocks

Synchronization method, a method of increasing the class synchronized modifier, such as

class A{
    public synchronized void classA() {
        System.out.print("ClassA");
    }
}

Sync block, synchronized modifier is increased in the code blocks, such as

class A{
    public void classB(){
       synchronized(this){System.out.print("classB")}
  }  
}

Operate together, they find sysnchronized synchronization and synchronization method this object is the same object.

Added directly synchronized synchronization method implemented in the lock method, a synchronization code block within the lock method, it is clear that the scope of lock synchronization method is relatively large, the range to be synchronized block dots, the larger the range of the general synchronization performance worse, generally need to be locked when synchronization is certainly scope as small as possible, so that better performance *.

First, when the same target object in two concurrent threads to access this synchronized (this) synchronized block, a time only one thread to be implemented. Another thread must wait for the current thread to execute the code block after the completion of the implementation of the code block. 
2. However, when a thread to access the object of a synchronized (this) synchronized block, another thread can still access the object in a non-synchronized (this) synchronized block. 
Third, it is particularly critical when a thread to access the object of a synchronized (this) synchronized block, another object of all other threads synchronized (this) to access the synchronization code block will be blocked.

Guess you like

Origin www.cnblogs.com/liujiata/p/11200907.html