[Java concurrent programming of the United States] synchroized keyword

synchronized keyword

  • synchronized block is a lock built atomic Java provided, each object can be to use it as a synchronization lock. Thread dollars into the synchronized automatically get inside the lock, this time will be blocked pending when other threads to access synchronized block.
  • synchronized can cause a lot of overhead, try to avoid unnecessary use.
  • Each set of locks for an object (/ load lock static methods and classes on time for all objects of a class) only one lock.

synchronized keyword can be modified following

1 synchronized modification of a method

public class SingletonPattern {
    public synchronized void method() {
        //todo
    }
}
  • If the sub-category covers the parent class synchronized modification of the method, the default is not inherited synchronized, plus synchronized necessary to be displayed.

2.1 synchronized block of code modification

    public void method() {
        //other part
        int num1;
        int num2;
        synchronized(this) {
            //todo
        }
    }
  • When a synchronized (this) one thread to access the object blocks of the synchronization code, still another thread may access the object in a non-synchronized (this) code sync blocks.

2.2 synchronized modification of a specified object

public class SingletonPattern {
    public void method(SomeObject obj) {
        synchronized(obj) {
            //todo
        }
    }
}

2.3 synchronized modification of a particular object. Want to sync block, there is no clear time to be locked object, you can lock a particular object

public class SingletonPattern {
    private byte[] lock = new byte[0];  // 特殊的instance变量
       public void method()
       {
          synchronized(lock) {
             // todo 同步代码块
          }
       }
}

3 synchronized modification of static methods

  • Lock the class, i.e. the class of all objects of a common lock.

4 synchronized modified class

class ClassName {
   public void method() {
      synchronized(ClassName.class) {
         // todo
      }
   }
}
  • Similarly, a shared lock all classes.

Reference links

https://blog.csdn.net/sinat_32588261/article/details/72880159

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11266906.html