【问题标题】:2 ways for synchronize, what is the difference [duplicate]2种同步方式,有什么区别[重复]
【发布时间】:2019-02-27 09:19:44
【问题描述】:

我找到了两种同步方法:

第一:

public static Integer number = 0;

 public synchronized static void myMethod(){
        number++;
        number--;
    }

第二个:

    public static Integer number = 0;
    private static final Object mySemaphoreLock = new Object();

public static void myMethod(){
        synchronized (mySemaphoreLock){
            number++;
            number--;
        }
    }

这两种方法是一样的吗?它们有什么区别?

【问题讨论】:

  • 方法远不止两种。这里的主要区别是锁对调用者(和其他所有人)可见的第一种方法,如果他们有权访问对象的引用,任何人都可以获取并持有该锁。

标签: java synchronized


【解决方案1】:

在第二种情况下,锁定对象仅适用于您的班级。 在第一种方法中,其他一些代码可能会意外或故意获得锁,从而使您的代码无法按预期工作。

例如,如果第一种情况可以执行以下操作

public class MyBadClass {

  public static void badStuff() {  //Acquire lock on class object and do forever loop. Because of that you will not be able to call YourClass.myMethod() in your first option
    synchronized (YourClass.class) {
      while(true);
    }
 }
}

【讨论】:

    【解决方案2】:

    这两种方法使用不同的对象进行同步(类实例与类字段)。


    你的第一种方法:

    public synchronized static void myMethod(){
        number++;
        number--;
    }
    

    可以表示为

    public static void myMethod(){
        synchronized (YourClass.class) {
            number++;
            number--;
        }
    }
    

    所以您使用不同的对象来同步(YourClass 的类对象与类的静态字段 (mySemaphoreLock))而不是

    public static void myMethod() {
        synchronized (mySemaphoreLock) {
            number++;
            number--;
        }
    }
    

    在您的示例中没有区别,但您不能排除其他人(想想 3rd-party 代码)想要在您的类的对象上同步(原因未知) - 这会影响你的代码的行为。 一般来说,它会是一些其他代码做类似的事情:

    class SomeOtherClass {
    
    public void someOtherMethod() {
        // for some reason SomeOtherClass synchronizes on YourClass.class
        synchronized (YourClass.class) {
            /* long running operation */
        }
    }
    
    }
    

    因此,即使您并行调用YourClass.myMethod(),也需要等待另一个完成。

    如果您选择使用mySemaphoreLock 实现,则不会发生这种情况 - 这段代码将同时执行(因为它们使用不同的对象进行同步) - 所以没有竞争。

    【讨论】:

    • 您能否展示可能影响我的代码的代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多