线程安全又不堵塞的单例模式
来源:互联网 发布:vscode 酷炫插件 编辑:程序博客网 时间:2024/04/30 08:31
单例模式,我们平常写的有好几种,下面有其中的五种
/**
* 单例模式1,存在线程不安全问题,若不考虑线程安全可以用*
* @author tarena
*
*/
class Singleton1 {
private static Singleton1 singleton;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (singleton == null) {
singleton = new Singleton1();
}
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
* 单例模式2,线程安全了,但会因为线程同步,引起线程堵塞
* 若是不考虑大并发情况下,也可以用。
* @author tarena
*
*/
class Singleton2 {
private static Singleton2 singleton;
private Singleton2() {
}
public synchronized static Singleton2 getInstance() {
if (singleton == null) {
singleton = new Singleton2();
}
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
/**
*
* @author tarena
*
*/
class Singleton3 {
private static Singleton3 singleton;
private Singleton3() {
}
public static Singleton3 getInstance() {
if (singleton == null) {
synchronized (Singleton3.class) {
if (singleton == null) {
singleton = new Singleton3();
}
}
}
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
* 单例模式4,线程安全了,并发访问速度更快了,
* 缺点:假如对象比较大,类加载时就创建了此对象,假如不使用,就可能长时间占用内存。
* @author tarena
*
*/
class Singleton4 {//非大对象时用
private static final Singleton4 singleton=new Singleton4();
private Singleton4(){
}
public static Singleton4 getInstance() {
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
* 单例模式5,线程安全了,并发访问速度更快了
*
* @author tarena
*
*/
class Singleton5 {//大对象时,就用这种
private Singleton5(){
}
//什么时候需要什么时候构建实例。
static class Lazy{
private static final Singleton5 singleton=new Singleton5();
}
public static Singleton5 getInstance() {
return Lazy.singleton;
}
}
以上五种供参考学习,推荐用第五种。
阅读全文
1 0
- 线程安全又不堵塞的单例模式
- 线程安全又支持延迟加载的单例模式——Initialization on demand holder
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- Volatile 线程安全的单例模式
- 线程安全的单例模式
- 基于线程安全的单例模式
- 线程安全的单例模式
- 单例模式的线程安全
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式
- 线程安全的单例模式 [老生常谈]
- java线程安全的单例模式
- 转:sklearn中的模型评估
- struts2 --- struts2值栈
- mysql基础练习
- windows下安装mysql5.6
- 深度思考比勤奋更重要
- 线程安全又不堵塞的单例模式
- GOOGLE 百度 YAHOO MSN 搜索引擎如何优化?各大特点是什么?
- MyEclipse_2017_C9_For_Windows torrent磁力链接下载地址 date_2017/12/23
- Nginx
- 函数式编程初步(lambda表达式)
- 热血传奇抢夺稀有精英怪技巧分享
- json的键值都为动态变量
- 我从阿里面试回来,想和Java程序猿谈一谈
- Day14作业 二、有两个List集合怎么取两个无重复的并集