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

查看:131
本文介绍了.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)用于确保块中只有一个Thread。 synchronized(this)确保每个实例只有一个线程。如果这使得块中线程安全的实际代码取决于实现。如果mutate只有实例的状态 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天全站免登陆