1、饿汉式是在单例类的实例在JVM启动时就创建好了,懒汉式则是在第一次访问单例类的实例时才去创建,即可以把饿汉式看成是预加载,懒汉式则为延迟加载;
示例代码:
public class EagerSingleton { private static final EagerSingleton instance = new EagerSingleton(); private EagerSingleton() { System.out.println("Initialized.."); } public static EagerSingleton getInstance() { return instance; } public void print() { System.out.println("This is an eager singleton."); } }
2、饿汉式的单例类实例由于是在JVM启动时创建的,所以不用考虑多线程问题,懒汉式则需要进行同步(synchronized);
示例代码:
public class LazySingleton { private static LazySingleton instance = null; private LazySingleton() { System.out.println("Initialized.."); } public static synchronized LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } public void print() { System.out.println("This is an lazy singleton."); } }