单例与线程安全
-
饿汉式--本身线程安全
在类加载的时候,就已经进行实例化,无论之后用不用到。如果该类比较占内存,之后又没用到,就白白浪费了资源
public class HungerSingleton { private static final HungerSingleton INSTANCE = new HungerSingleton(); private HungerSingleton() { } public static HungerSingleton getInstance() { return INSTANCE; } 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 instance = null; private LazySingleton() { } public static LazySingleton getInstance() { if (instance == null) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (LazySingleton.class) { if (instance == null) { instance = new LazySingleton(); } } } return instance; } public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(() -> { System.out.println(LazySingleton.getInstance()); }).start(); } } }