懒汉和饿汉单例的区别

来源:互联网 发布:软件项目助理招聘 编辑:程序博客网 时间:2024/06/07 00:43

首先来看饿汉单例模式:

public class EagerSingleton {
    private EagerSingleton(){
       
    }
   
    private static EagerSingleton instance = new EagerSingleton();  //饿汉式在类被创建的时候就创建实例
   
    public static EagerSingleton getInstance(){
        return instance;
    }
}

 

下面来看下懒汉单例模式:

 

public class LazeSingleton {
    private LazeSingleton(){
       
    }
   
    private static LazeSingleton instance = null; //懒汉式单例是延时加载,什么时候用什么时候创建实例
   
    public static LazeSingleton getInstance(){
        if(instance == null){
            instance = new LazeSingleton();   //创建实例
        }
        return instance;
    }
}

 

饿汉式是线程安全的,在类被创建的时候就被创建了一个静态的对象供系统使用,以后不再改变

懒汉式如果在创建时不被加上synchronized则会导致对象的访问不是线程安全的

推荐使用第一种

原创粉丝点击