1、饿汉式,JVM保证线程安全(构造器私有化)
public class HongYan01 {
private static final HongYan01 INSTANCE = new HongYan01();
private HongYan01() {};
public static HongYan01 getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
System.out.println(HongYan01.getInstance() == HongYan01.getInstance());
}
}
2、双重校验机制,线程安全,懒加载(构造器私有化)
public class HongYan02 {
// 懒加载,双重校验机制
private static volatile HongYan02 singleton;
private HongYan02() {
}
public static HongYan02 getInstance() {
if (singleton == null) {
// 双重检查
synchronized (HongYan02.class) {
if(singleton == null) {
singleton = new HongYan02();
}
}
}
return singleton;
}
public static void main(String[] args) {
for(int i=0; i<666; i++) {
new Thread(()-> System.out.println(HongYan02.getInstance().hashCode())).start();
}
}
}
3、静态内部类单例,jvm加载类保证单例,线程安全
public class HongYan03 {
private HongYan03() {
}
private static class HongYan03InnerClass {
private final static HongYan03 INSTANCE = new HongYan03();
}
public static HongYan03 getInstance() {
return HongYan03InnerClass.INSTANCE;
}
public static void main(String[] args) {
for(int i=0; i<666; i++) {
new Thread(()-> System.out.println(HongYan03.getInstance().hashCode())).start();
}
}
}
4、枚举方式,实现单例,线程安全,还可以防止反序列化
public enum HongYan04 {
INSTANCE;
public static void main(String[] args) {
for (int i = 0; i < 666; i++) {
new Thread(() -> System.out.println(HongYan04.INSTANCE.hashCode())).start();
}
}
}
其他方式可能会导致线程不安全,这里不进行展示错误示例了。