简体   繁体   English

同步块相当于静态同步方法?

[英]Synchronized block equivalent to static synchronized method?

When you have a method such as the following: 如果您有如下方法:

public synchronized void addOne() {
    a++;
}

it is equivalent to the following: (correct me if I'm wrong) 它等同于以下内容:(如果我错了,请纠正我)

public void addOne() {
    synchronized(this) {
        a++;
    }
}

But what is the equivalent to the following method?: 但是什么相当于以下方法?:

public static synchronized void addOne() {
    a++;
    // (in this case 'a' must be static)
}

What is a synchronized block that acts the same as a static synchronized method? 什么是同步块,其作用与静态同步方法相同? I understand the static synchronized method is synchronized on the class and not the instance (since there is no instance), but what is the syntax for that? 我理解静态同步方法是在类而不是实例上同步的(因为没有实例),但是它的语法是什么?

It is equivalent to locking on the class object. 它等同于锁定类对象。 You can get a reference to the class object by writing the class name followed by .class . 您可以通过编写类名称后跟.class来获取对类对象的引用。 So, something like: 所以,像:

synchronized(YourClass.class) {
}

See the Java Language Specification, Section 8.4.3.6 synchronized Methods : 请参阅Java语言规范,第8.4.3.6节synchronized方法

A synchronized method acquires a lock (§17.1) before it executes. synchronized方法在执行之前获取锁(第17.1节)。 For a class (static) method, the lock associated with the Class object for the method's class is used. 对于类(静态)方法,使用与方法类的Class对象关联的锁。 For an instance method, the lock associated with this (the object for which the method was invoked) is used. 对于实例方法,使用与此关联的锁(调用该方法的对象)。

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

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