單例保證一個對象JVM中只能有一個實例,常見單例 懶漢式、餓漢式安全
什麼是懶漢式,就是須要的纔會去實例化,線程不安全。spa
什麼是餓漢式,就是當class文件被加載的時候,初始化,天生線程安全。線程
懶漢式代碼code
class SingletonTest { public static void main(String[] args) { Singleton sl1 = Singleton.getSingleton(); Singleton sl2 = Singleton.getSingleton(); System.out.println(sl1 == sl2); } } public class Singleton { // 當須要的纔會被實例化 private static Singleton singleton; private Singleton() { } static public Singleton getSingleton2() { //雙重檢驗鎖 if (singleton == null) { // 第一步檢驗鎖 synchronized (Singleton.class) { // 第二步檢驗鎖 if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
餓漢式代碼對象
class SingletonTest1 { public static void main(String[] args) { Singleton1 sl1 = Singleton1.getSingleton(); Singleton1 sl2 = Singleton1.getSingleton(); System.out.println((sl1 == sl2)+"-"); } } public class Singleton1 { //當class 文件被加載初始化 private static Singleton1 singleton = new Singleton1(); private Singleton1() { } public static Singleton1 getSingleton() { return singleton; } }