简体   繁体   English

从另一个同步方法调用同步方法,两者都在不同的 object

[英]Calling a synchronized method from another synchronized method, both on different object

Lets say we have two classes A, B and synchronized methods methodA, methodB of the respective classes.假设我们有两个类 A、B 和各个类的同步方法 methodA、methodB。 If we call synchronized methodB from synchronized methodA whether the thread still hold lock on ObjectA while methodB is still executing?如果我们从同步的方法A调用同步的方法B,当方法B仍在执行时,线程是否仍然持有对象A的锁?

Class A
{
   public synchronized void methodA()
   {
       //do something;
       synchronized(ObjectB)
       {
          ObjectB.methodB();
       }
   }
}

Class B
{
   public synchronized void methodB()
   {
      //do something
   }
}

The lock will held as long as you are in sync block.只要您处于同步块中,锁定就会保持。 It is allowed to lock as many locks as you need but this nested synchronization can impact the overall performance of your application.可以根据需要锁定尽可能多的锁,但这种嵌套同步会影响应用程序的整体性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM