饿汉式–线程安全
在类加载的时候,就已经进行实例化,无论之后用不用到。如果该类比较占内存,之后又没用到,就白白浪费了资源。
public class HungerSingleton {
private static HungerSingleton ourInstance = new HungerSingleton();
public static HungerSingleton getInstance() {
return ourInstance;
}
private HungerSingleton() {
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(()->{
System.out.println(HungerSingleton.getInstance());
}).start();
}
}
}
懒汉式 – 最简单的写法是非线程安全的
在需要的时候再实例化
public class LazySingleton {
private static volatile LazySingleton lazySingleton = null;
private LazySingleton() {
}
public static LazySingleton getInstance() {
//判断实例是否为空,为空则实例化
if (null == lazySingleton) {
//模拟实例化时耗时的操作
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (LazySingleton.class) {
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
}
}
//否则直接返回
return lazySingleton;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(LazySingleton.getInstance());
}).start();
}
}
}