-
饿汉式--本身线程安全
在类加载的时候,就已经进行实例化,无论之后用不用到。如果该类比较占内存,之后又没用到,就白白浪费了资源。
-
懒汉式 -- 最简单的写法是非线程安全的
在需要的时候再实例化
-
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; } }
单例与线程安全
最新推荐文章于 2024-04-04 11:40:27 发布