与静态块同步

DJh*_*hon 2 java static synchronization

我有一个问题:我们可以在 方法中使用static关键字synchronized吗?众所周知,静态与类相关,同步用于阻塞对象,使用synchronizedwith static对我没有任何意义.那么为什么以及在哪种情况下我会使用与static关键字的同步?

Abi*_*san 8

在java中,静态内容在方法定义的类对象上同步,

例如

static synchronized void aMethod() {} 相当于

static void aMethod() {
      synchronized(YourClass.class){

      }
}
Run Code Online (Sandbox Code Playgroud)

来自JLS 8.4.3.6

synchronized方法在执行之前获取锁(第17.1节).对于类(静态)方法,使用与方法类的Class对象关联的锁.对于实例方法,使用与此关联的锁(调用该方法的对象).

OP的问题:

为什么我使用静态同步和"情况"?

情况是防止多个Thread同时执行静态方法.