如何获取类级别锁定

Ani*_*kur 7 java static synchronization locking

public synchronized int getCountOne() {
        return count++;
 }
Run Code Online (Sandbox Code Playgroud)

与上面的代码一样,在方法上的同步在功能上等同于在方法synchronized (this) block的主体周围.对象"this"不会被锁定,而是将"this"作为对象使用,mutex并防止正文与同时在"this"上同步的其他代码段同时执行.

在类似的理由上,mutex当我们获得一个类级锁时,我们会使用它.如果我们有一个函数

public static synchronized int getCountTwo() {
        return count++;
 }
Run Code Online (Sandbox Code Playgroud)

显然,两个线程可以同时获取getCountOne(对象级别锁定)和getCountTwo(类级别锁定)的锁定.因此getCountOne类似于

public int getCountOne() {
     synchronized(this) {
          return count++;
     }
 }
Run Code Online (Sandbox Code Playgroud)

是否有相当于getCountTwo?如果没有使用什么标准来获得类级别锁定?

Roh*_*ain 10

在类似的理由中,当我们获得类级锁时,它被用作互斥体

类对象本身将用作互斥锁.您static synchronized方法的等效同步块如下所示:

public static int getCountTwo() {
     synchronized(ClassName.class) {
          return count++;
     }
}
Run Code Online (Sandbox Code Playgroud)

ClassName 是包含该方法的类的名称.

JLSSection§8.4.3.6:

同步方法在执行之前获取监视器(第17.1节).

对于类(静态)方法,使用与方法类的Class对象关联的监视器.

对于实例方法,使用与此关联的监视器(调用该方法的对象).

强调我的.