1 单例的饿汉式
对象在类加载的时候就创建了,线程安全,速度块,但是浪费空间,
public class Hungry {//唯一对象private static final Hungry HUNGRY = new Hungry();byte byte1[]=new byte[1024];byte byte2[]=new byte[1024];byte byte3[]=new byte[1024];//构造器私有,防止外部new新的对象private Hungry() {}public static Hungry getInstance() {return HUNGRY;}
}
2单例的懒汉式
public class LazyMan {private static LazyMan lazyMan;private LazyMan() {}public static LazyMan getInstance() {if (lazyMan == null) {lazyMan = new LazyMan();}return lazyMan;}public static void main(String[] args) {for (int i = 0; i < 10; i++) {new Thread(()-> System.out.println(LazyMan.getInstance())).start();}}
}
懒汉式单例创建对象慢,省内存,但是线程不安全
如图产生了两个对象
双重检测锁搞定线程安全问题
懒汉式单例的双重检测锁==DCL懒汉式
public static LazyMan getInstance() {if (lazyMan == null) {//因为怕加锁之前lazyMan!=null,所以加双重检测synchronized (LazyMan.class) {if (lazyMan == null) {lazyMan = new LazyMan();}}}return lazyMan;}