.class 的 Java 同步块 [英] Java Synchronized Block for .class

查看:26
本文介绍了.class 的 Java 同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段java代码是什么意思?它会锁定 MyClass 的所有对象吗?

What does this java code mean? Will it gain lock on all objects of MyClass?

synchronized(MyClass.class) {
   //is all objects of MyClass are thread-safe now ??
}

以上代码与此代码有何不同:

And how the above code differs from this one:

synchronized(this) {
   //is all objects of MyClass are thread-safe now ??
}

推荐答案

片段 synchronized(X.class) 使用类实例作为监视器.由于只有一个类实例(在运行时表示类元数据的对象),因此该块中可以有一个线程.

The snippet synchronized(X.class) uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) one thread can be in this block.

使用 synchronized(this) 块由实例保护.对于每个实例,只有一个线程可以进入块.

With synchronized(this) the block is guarded by the instance. For every instance only one thread may enter the block.

synchronized(X.class) 用于确保块中只有一个线程.synchronized(this) 确保每个实例只有一个线程.如果这使得块中的实际代码线程安全取决于实现.如果只改变实例的状态 synchronized(this) 就足够了.

synchronized(X.class) is used to make sure that there is exactly one Thread in the block. synchronized(this) ensures that there is exactly one thread per instance. If this makes the actual code in the block thread-safe depends on the implementation. If mutate only state of the instance synchronized(this) is enough.

这篇关于.class 的 Java 同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆