In one instance, multiple synchronized method calls

A more popular and simple question:  "Can two threads in Java access two different synchronized methods of an object at the same time ??"

The answer is: no!!!


[java]  view plain copy  
  1. publicclass ThreadA extends Thread {   
  2.     private MyObject object;  
  3.   
  4.     public ThreadA(MyObject object){  
  5.         this.object = object;  
  6.     }  
  7.   
  8.     publicvoid run(){   
  9.         super.run();  
  10.         object.menthodA();  
  11.     }  
  12. }  


[java]  view plain copy  
  1. publicclass ThreadB extends Thread {   
  2.     private MyObject object;  
  3.   
  4.     public ThreadB(MyObject object){  
  5.         this.object = object;  
  6.     }  
  7.   
  8.     publicvoid run(){   
  9.         super.run();  
  10.         object.methodB();  
  11.     }  
  12. }  

[java]  view plain copy  
  1. publicclass Run {   
  2.     public static void main(String args[]){  
  3.         MyObject myObject = new MyObject();  
  4.         ThreadA threadA = new ThreadA(myObject);  
  5.         threadA.setName("A");  
  6.         threadA.start();  
  7.         ThreadB threadB = new ThreadB(myObject);  
  8.         threadB.setName("B");  
  9.         threadB.start();  
  10.     }  
  11. }  

代码如上所示,MyObject类有两个方法,分别创建两个线程调用方法A和方法B:

1、方法A和方法B都没有加synchronized关键字时,调用方法A的时候可进入方法B;

2、方法A加synchronized关键字而方法B没有加时,调用方法A的时候可以进入方法B;

3、方法A和方法B都加了synchronized关键字时,调用方法A之后,必须等A执行完成才能进入方法B;

4、方法A和方法B都加了synchronized关键字时,且方法A加了wait()方法时,调用方法A的时候可以进入方法B;

5、方法A加了synchronized关键字,而方法B为static静态方法时,调用方法A的时候可进入方法B;

6. Both method A and method B are static static methods, and the synchronized keyword is added. After calling method A, you need to wait for the execution of method A to complete before entering method B;

7. Method A and method B are both static static methods, and the synchronized keyword is added to create different threads to call A and B respectively. It needs to wait for the execution of A to complete before executing B (because the static method is a single instance, A holds Some are Class locks, and Class locks can work on all object instances of the class)

Summarize:

When the synchronized keyword is added to multiple methods in the same object, after calling any method, it needs to wait for the execution of the method to complete before calling other methods, that is, synchronized or blocked ;

This conclusion also applies to the use of synchronized (this) synchronized code blocks in objects;

Synchronized locks the current object!


Reprinted from: https://blog.csdn.net/aiyawalie/article/details/53261823

Guess you like

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