单例模式
这里主要讲一下懒汉模式和恶汉模式 1) 懒汉模式: //懒汉模式 public class LazySingle { private static LazySingle sInstance = null; private LazySingle() {} public static LazySingle getInstance() { if (sInstance == null) { sInstance = new LazySingle(); } return sInstance; } } 这是非线程安全的写法,在多线程并发执行的时候,就会很容易出现安全隐患。 优点:懒加载启动快,资源占用小,使用时才实例化,无锁。 缺点:不安全 接下来看看线程安全的写法,其实就是加个锁 public class LazySingle { private static LazySingle sInstance = null; private LazySingle() {} public static LazySingle getInstance() { if (sInstance == null) { synchronized (LazySingle.class) { if (sInstance == null) { sInstance = new LazySingle(); } } } return