阅读背景:

JAVA单例实现方式(常用)

来源:互联网 

JAVA单例实现方式(常用)

public class Singleton {
    // Q1:为什么要使用volatile关键字?
    private volatile static Singleton uniqueInstance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            /* Q2:为什么要使用synchronized (Singleton.class),使用synchronized(this)或者
            synchronized(uniqueInstance)不行吗?而且synchronized(uniqueInstance)的效率更加高?*/
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                 }
            }
        }
        return uniqueInstance;
    }
}public class Singleton {
    /



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: