我已经读到synchronized void f() { /* body */ }等效于
void f() { synchronized (this) { /* body */ } }

因此,当我们对单例的get方法执行synchronization时,将在哪个对象上进行同步。是Class还是Object?

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 */
    }
}

最佳答案

您正在类级别获得锁,即同步方法中的静态方法,因此YouObject.class上的同步等效于静态方法同步。同样,您将无法在静态方法中引用this,因为this引用了当前对象或该对象。

所以这:

public static synchronized YourObject getInstance() {


上面的代码相当于

synchronized (YourObject.class) {

07-24 09:15