我们为什么要写Synchronized(ClassName.class) [英] Why do we write Synchronized(ClassName.class)
问题描述
我对单例模式有疑问. 在单例模式中,我们编写
I have a question in singleton pattern. In singleton pattern we write
synchronized(ClassName.class){
// other code goes here
}
编写ClassName.class
的目的是什么?
推荐答案
在成员方法(非静态)中,您可以选择使用哪个监视器(锁定)两个选择:" this "和" 我班级的单个静态锁 ".
In a member method (non-static) you have two choices of which monitor (lock) to use: "this" and "my class's single static lock".
如果您要协调对象实例上的锁,请使用" 此 ":
If your purpose is to coordinate a lock on the object instance, use "this":
...
synchronized (this) {
// do critical code
}
或
public synchronized void doSomething() {
...
}
但是,如果您尝试进行安全操作,包括以下任何一项:
However, if you are trying to have safe operations including either:
-
静态方法
static methods
班上的静态成员
然后获取一个全班级锁至关重要.有两种方法可以同步静态锁:
Then it is critical to grab a class-wide-lock. There are 2 ways to synchronize on the static lock:
...
synchornized(ClassName.class) {
// do class wide critical code
}
或
public static synchronized void doSomeStaticThing() {
...
}
非常重要,以下两种方法请勿在同一锁上进行协调:
VERY IMPORTANTLY, the following 2 methods DO NOT coordinate on the same lock:
public synchronized void doMemberSomething() {
...
}
和
public static synchronized void doStaticSomething() {
...
}
这篇关于我们为什么要写Synchronized(ClassName.class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!