单例模式——多线程优化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gease_Gg/article/details/88599957

double-check 和 synchronized 实现单例模式在多线程下的优化。

 public class Singleton {
        private volatile static Singleton s=null;
        private Singleton(){}
        public static Singleton getInstance(){
            if(s==null){
                synchronized (Singleton.class){
                    if(s==null){
                        s=new Singleton();
                    }
                }
            }
            return s;
        }
        public static void print(){
            System.out.print("this is the print function");
        }
        public static void main(String[] args){
            Singleton s=Singleton.getInstance();
            s.print();
        }
    }

1.为什么不在成员变量里直接new?
没有必要在类加载时就实例化,节省空间。
2.synchronized有什么作用
防止多线程下会创建多个实例。
3.为什么synchronized里还有一个null判断
第一个线程创建后,后面线程就没有必要创建了,所以s是volatile定义的。

猜你喜欢

转载自blog.csdn.net/Gease_Gg/article/details/88599957
今日推荐