开发者

Synchronized block equivalent to static synchronized method?

开发者 https://www.devze.com 2023-01-08 23:25 出处:网络
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)

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. So, something like:

synchronized(YourClass.class) {
}

See the Java Language Specification, Section 8.4.3.6 synchronized Methods:

A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method, the lock associated with the Class object for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号