详细探究单例模式

前言

今天学习了单例模式,以前写图书管理系统的时候,了解过单例模式。而如今随着学习到了线程。把单例模式放在线程中进行考虑。与以前在单线程的单例模式相比,多线程的单例模式会考虑更多的问题,与大家分享一波~

单例模式的详细分析(思考的点一步一步深入)

代码 

懒汉式

class SingletonLazy{
    private static Object locker=new Object();
    private static volatile SingletonLazy instance=null;
   public static SingletonLazy getInstance(){
       if(instance==null) {
           synchronized (locker) {
               if (instance == null) {
                   instance = new SingletonLazy();
               }
           }
       }
           return instance;
   }
   private SingletonLazy(){

   }
}
public class demo34 {
    public static void main(String[] args) {
        SingletonLazy s1=SingletonLazy.getInstance();
        SingletonLazy s2=SingletonLazy.getInstance();
        System.out.println(s1==s2);

    }

}

饿汉式 

class Singleton{
    private static Singleton instance=new Singleton();
    public static Singleton getInstance(){
        return instance;
    }
    private Singleton(){

    }
}

public class demo33 {
    public static void main(String[] args) {
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();
        System.out.println(s1==s2);
    }
}

结语 

一句话总结,单线程只管用单例模式就对了,而多线程要考虑得就多了~祝大家端午安康~

 

 

 

 

你可能感兴趣的:(单例模式,java,开发语言)