.class 的 Java 同步块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2056243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Synchronized Block for .class
提问by
What does this java code mean? Will it gain lock on all objects of MyClass
?
这个java代码是什么意思?它会锁定 的所有对象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 ??
}
采纳答案by Thomas Jung
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(X.class)
使用类实例作为监视器。由于只有一个类实例(在运行时表示类元数据的对象),因此该块中可以有一个线程。
With synchronized(this)
the block is guarded by the instance. For every instance only one thread may enter the block.
随着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.
synchronized(X.class)
用于确保块中恰好只有一个线程。synchronized(this)
确保每个实例只有一个线程。如果这使得块中的实际代码线程安全取决于实现。如果只改变实例的状态synchronized(this)
就足够了。
回答by David M
No, the first will get a lock on the class definition of MyClass
, not all instances of it. However, if used in an instance, this will effectively block all other instances, since they share a single class definition.
不,第一个将锁定 的类定义MyClass
,而不是它的所有实例。但是,如果在实例中使用,这将有效地阻止所有其他实例,因为它们共享单个类定义。
The second will get a lock on the current instance only.
第二个将仅锁定当前实例。
As to whether this makes your objects thread safe, that is a far more complex question - we'd need to see your code!
至于这是否使您的对象线程安全,这是一个复杂得多的问题 - 我们需要查看您的代码!
回答by Jorn
To add to the other answers:
要添加到其他答案:
static void myMethod() {
synchronized(MyClass.class) {
//code
}
}
is equivalent to
相当于
static synchronized void myMethod() {
//code
}
and
和
void myMethod() {
synchronized(this) {
//code
}
}
is equivalent to
相当于
synchronized void myMethod() {
//code
}