简体   繁体   English

同步方法而不是Java中的同步语句

[英]synchronized method instead of synchronized statement in java

I have a method with a synchronization statement on an "non-this" object 我有一个方法在“ non-this”对象上带有同步语句

class Some_Class { 
  public A s = new A();
  public void method_A() { 
    synchronized(s) { 
      ....
    } 
  }
}

Can I instead extend class A and synchronize as follows: 我可以改为扩展类A并按以下方式进行同步:

class B extends A {  
  public A a;
  public B(A a) {  
    this.a = a; 
  }  
  public synchronized void some_m() {  
    ...  
  }  
}   
class Some_Class {  
  public A s = new A();
  public void method_A() {
    B b = new B(s);
    b.some_m();
  }  
} 

Are these two synchronizations equivalent? 这两个同步等效吗?

No, they're not equivalent. 不,它们不相等。 This method here: 这种方法在这里:

public synchronized void some_m() {  
  ...  
}

Does the same as this one: 与此相同:

public void some_m() {  
    synchronized(this) {
        ...  
    }
}  

Or in other words 或者换句话说

  1. Your first code option synchronises on an instance of A in Some_Class (a class member, visible to everyone). 您的第一个代码选项在Some_ClassA实例(类成员,所有人可见)上同步。
  2. Your second code option synchronises on the instance of B within Some_Class.method_A() (a local variable, invisible to the outside of that method) 您的第二个代码选项与Some_Class.method_A()B实例同步(本地变量,该方法外部不可见)

No, they are not equivalent. 不,它们不是等效的。 In second case you actually don't have synchronization at all. 在第二种情况下,您实际上根本没有同步。 Because some_m method synchronized on instance of B . 因为some_m方法在B实例上同步。 So you create local instance of B and call method on it. 因此,您将创建B的本地实例并在其上调用方法。 This method is synchronized only on this local instance of B and other threads don't care about it and can do whatever they want with s because it's not synchronized. 此方法仅在B的该本地实例上同步,其他线程对此并不关心,并且可以使用s进行任何操作,因为它不同步。
Can you describe what you want to achieve? 您能描述您想要实现的目标吗?

Synchronized block synchronizes the whole object while synchronized method synchronizes just that method. 同步块同步整个对象,而同步方法仅同步该方法。 In the second case, some thread can still access other non-synchronized methods of the object. 在第二种情况下,某些线程仍可以访问该对象的其他非同步方法。

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

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