美文网首页
单例模式代码

单例模式代码

作者: Mr_Gao_ | 来源:发表于2018-05-25 17:26 被阅读0次
    public class Singleton {
        private static volatile Singleton uniqueInstance;
    
        public static Singleton getInstance(){
            if(uniqueInstance == null){ //#1
                synchronized(Singleton.class){ //#2
                    if(uniqueInstance == null){ //#3
                        uniqueInstance = new Singleton(); //#4
                        System.out.println(Thread.currentThread().getName() + ": uniqueInstance is initalized..."); //#5.1
                    } else {
                        System.out.println(Thread.currentThread().getName() + ": uniqueInstance is not null now..."); //#5.2
                    }
                }
            }
            return uniqueInstance;
        }
    }
    

    相关文章

      网友评论

          本文标题:单例模式代码

          本文链接:https://www.haomeiwen.com/subject/pbyujftx.html