Android 开发小经验
16lz
2021-01-23
单例的写法
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }}
但是这种写法线程不安全,于是我们会加个锁,这样写
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }}
网上大部分都这样写 ,bingo 这样写完全没有问题,但是这样写效率比较低,
在Java1.5就引入了一个新的关键字—volatile,现在就有了双重检验校验的写法:
public class Singleton { private static volatile Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class){ if (instance == null) { instance = new Singleton(); } } } return instance; }}
上面这种方法用的比较多,这里还有一种静态final的写法
public class Singleton { private Singleton() {} private static class SingletonLoader { private static final Singleton INSTANCE = new Singleton(); }; public static Singleton getInstance() { return SingletonLoader.SINGLETOP_INSTANCE; }}
更多相关文章
- Android 读写文件的N种写法
- Android子线程与子线程的通信
- android子线程中刷新界面控件
- android 主线程和子线程之间的消息传递
- android编程之在单线程模型中Message、Handler、Message Queue、
- Android 进程和线程模型 .
- Android中Handler异步线程