概述
在类加载后,整个系统只有一个实例类
饿汉式
public class Mg1 {private static final Mg1 INSTANCE = new Mg1();private Mg1(){}public static Mg1 getInstance(){return INSTANCE;}public static void main(String[] args) {System.out.println(Mg1.getInstance() == Mg1.getInstance());// true}
}
懒汉式
/*** 会存在内部不安全问题*/
public class Main {public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(()->{System.out.println(Mg2.getInstance().hashCode());}).start();}}
}
class Mg2 {private static Mg2 INSTANCE;private Mg2(){}public static synchronized Mg2 getInstance(){if(INSTANCE == null){try{Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}INSTANCE = new Mg2();}return INSTANCE;}
}
静态内部类
/*** 静态内部类* 懒加载*/
public class Mg3 {private Mg3(){}private static class Mg3Holder{private final static Mg3 INSTANCE = new Mg3();}public static Mg3 getInstance(){return Mg3Holder.INSTANCE;}public static void main(String[] args) {new Thread(()->{for (int i = 0; i < 100; i++) {System.out.println(Mg3.getInstance().hashCode());}}).start();}
}
枚举单例
/*** 枚举单例* 不仅可以解决线程同步,还可以反序列化*/
public enum Mg4 {INSTANCE;public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(()->{System.out.println(Mg4.INSTANCE.hashCode());}).start();}}
}