gpt4 book ai didi

java - Singleton 实例是在什么上同步的?

转载 作者:行者123 更新时间:2023-12-01 22:32:40 25 4
gpt4 key购买 nike

我读过synchronized void f() { /* body */ }相当于
void f() { synchronized (this) { /* body */ } }

所以当我们做 synchronization单例的 get 方法我们正在同步哪个对象。是还是对象

public class YourObject {
private static YourObject instance;

private YourObject() { }

public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
}

这相当于-

public static YourObject getInstance() {
synchronized (this) {
/* body */
}
}

public static YourObject getInstance() {
synchronized (YourObject.class) {
/* body */
}
}

最佳答案

我们来问问the documentation :

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

所以:

public static YourObject getInstance() {
synchronized (YourObject.class) {
/* body */
}
}

相当于你的代码

关于java - Singleton 实例是在什么上同步的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27378527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com