java单例模式(饿汉式,懒汉式)
------改进后线程安全------
// 懒汉式 class LazySingleton { // 私有化构造器 private LazySingleton() {} // 类的内部创建实例 private static LazySingleton instance = null; public static LazySingleton getInstance() { if (instance == null) { // 外面加一层的原因:if判断比synchronized效率高 synchronized (LazySingleton.class) { if (instance == null) { instance = new LazySingleton(); } } } return instance; } } // 测试输出的地址是否一致 public class SingletonTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread() { @Override public void run() { System.out.println(LazySingleton.getInstance()); } }.start(); } } }
------本身线程安全------
// 饿汉模式 class HungrySingleton { // 私有化构造器 private HungrySingleton() {} private static HungrySingleton instance = new HungrySingleton(); public static HungrySingleton getInstance() { return instance; } } // 测试输出的地址是否一致 public class SingletonTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread() { @Override public void run() { System.out.println(HungrySingleton.getInstance()); } }.start(); } } }
                    
                
                
            
        
浙公网安备 33010602011771号