完美的单例模式

在多线程下懒加载保证只实例化一次。

第一种双重判断:

public class SingletonTest {
private static SingletonTest INSTANCE;

private SingletonTest() {
}

public static SingletonTest getInstance() {
if (INSTANCE == null) {
synchronized (SingletonTest.class) {
if (INSTANCE == null) {
INSTANCE = new SingletonTest();
}
}
}
return INSTANCE;
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
System.out.println(SingletonTest.getInstance().hashCode());
}).start();
}
}
}

第二种内部类,JVM会保证内部类只加载一次:

public class SingletonTest {

private SingletonTest() {
}

private static class SingletonTestInnerClass {
private static final SingletonTest INSTANCE = new SingletonTest();
}

public static SingletonTest getInstance() {
return SingletonTestInnerClass.INSTANCE;
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
System.out.println(SingletonTest.getInstance().hashCode());
}).start();
}
}
}

第三种使用枚举:

public enum SingletonTestEnum {
INSTANCE;

public void test() {
}

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
System.out.println(SingletonTestEnum.INSTANCE.hashCode());
}).start();
}
}
}

 

注:这些是自己学习的笔记,如有不准确,欢迎指出!

posted @ 2021-06-19 21:57  古月大海  阅读(67)  评论(0)    收藏  举报