Synchronized of Java keywords

Synchronized

  is a keyword for multi-thread synchronization in java. Usually we can understand it as a lock. I vaguely remember a case told by a teacher in college. There is a girl with an elegant temperament, and all men want to marry her, but China is monogamous. If a man registers marriage with her, then other men can't do anything, because this man has a lock (you can It is understood as a marriage certificate), unless she is divorced (without a marriage certificate, there is no lock), then other men can pursue her. to marry her. From this case, we roughly understand why there is a lock (monogamity), and the function of the lock.
In java code, Synchronized can usually modify the following objects.
1. Modify a method.
     There are usually two ways of writing:

     The first:

public synchronized void test(){
System.out.println(Thread.currentThread().getId());
}    

     The second:

public void test(){
synchronized (this) {
System.out.println(Thread.currentThread().getId());  
    }
}            

For this test method , their functions are the same, but if the current class has other methods modified with synchronized(this), they will be different.

2. Modify a class 
  Usually the method synchronized(***.class) is roughly similar to the first one, compared with the modified method. It's just that the scope of the lock is larger.

public void test(){
synchronized (FirstInstanceAlgori.class) {
System.out.println(Thread.currentThread().getId());
    }
}            

3. Decorate an internal object
 as shown below,

public Byte[] lock = new Byte[0];

public void test(){
synchronized (lock) {
System.out.println(Thread.currentThread().getId());
    }
}            

To sum up, 1. No matter who synchronized is modified, in the first step we need to clarify who is locking (the scope of the lock) and who owns the lock.
          2. After clarifying the first point, we should understand that the synchronized keyword cannot be inherited, it is responsible for locking the part that it is currently responsible for.
   3. In addition to modifying a method, modifying a class, modifying an internal object, or modifying a static method, their connotations are the same.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325162326&siteId=291194637