synchronized in java (the difference between synchronized code blocks and synchronized methods)

The origin of the problem:

See this interview question:

//下列两个方法有什么区别
public synchronized void method1(){}

public void method2(){
 synchronized  (obj){}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Synchronization is used to solve the synchronization problem. When multiple threads access shared data at the same time, if synchronization is not performed, an error will occur. The solution provided by java is: as long as the statement that operates the shared data is executed by one thread at a certain period of time End, during the execution process, other threads cannot come in and execute. solve this problem. There are two ways to use synchronized here, one is the above synchronization method, that is, the method is decorated with synchronized, and the other is the provided synchronization code block.

It always feels weird here. What is the difference between these two methods? I didn't learn the basics well, so I did a simple test. The code is as follows:

public class SynObj {
    public synchronized void methodA() {
        System.out.println("methodA.....");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public  void methodB() {
        synchronized(this) {
            System.out.pritntln("methodB.....");
        }
    }

    public void methodC() {
        String str = "sss";
        synchronized (str) {
            System.out.println("methodC.....");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
public class TestSyn {
    public static void main(String[] args) {
        final SynObj obj = new SynObj();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                obj.methodA();
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                obj.methodB();
            }
        });
        t2.start();

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                obj.methodC();
            }
        });
        t3.start();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

This small code snippet prints the result as follows:

methodA.....
methodC.....
//methodB会隔一段时间才会打印出来
methodB.....
  • 1
  • 2
  • 3
  • 4

The print result of this code is that methodA…..methodC….. will be printed out very quickly, and methodB….. will be printed out after a period of time, so why can’t methodB be called as quickly as methodC?

After starting thread 1 and calling method A, thread 1 will sleep for 5 seconds, and then method C will be called. Note that method C uses synchronized to lock, and the object of the lock here is the string object str. But method B is different. It uses the current object this to lock. Notice that method A directly adds synchronized to the method. What is the locked object? Obviously, these two methods use a lock.

*From this result, we know what lock is used for this synchronization method. Since thread 1 is sleeping and the lock has not been released at this time, thread 2 can only call method B after 5 seconds. From this, it can be seen that The two locking mechanisms use the same lock object, the current object.
In addition, the synchronization method directly adds synchronized to the method to achieve locking, and the synchronization code block is locked inside the method. Obviously, the scope of the synchronization method lock is relatively large, while the scope of the synchronization code block is smaller, and the larger the scope of synchronization is generally. , the worse the performance, generally when you need to lock for synchronization, the smaller the range, the better, so the performance is better*.

Guess you like

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