单例模式


/** *//**
* @author lx
* 线程不安全的单例,试想两个线程都进入了if(singleton==null)块里这个时候会初始化两个对象,这只在第一次调用的时候会产生
*/
public class Unsafe_singleton {

private static Unsafe_singleton singleton;

private Unsafe_singleton() {
}

public static Unsafe_singleton getInstance() {
if (singleton == null) {
singleton = new Unsafe_singleton();
}
return singleton;
}
}
public class Safe_singleton {

private static Safe_singleton singleton;

private Safe_singleton() {
}

/** *//**
* 这种写法,非常消耗性能,因为只是第一次进来的时候可能会产生多个实例的情况,后面多线程都不会再进行实例化,那么调用的时候会很降低性能
* @return
*/
public static synchronized Safe_singleton getInstance() {
if (singleton == null) {
singleton = new Safe_singleton();
}
return singleton;
}
}
/** *//**
* @author lx
* 这种写法如果在创建和运行时的负担不太繁重,那么这种写法也可以保证多线程安全,每个线程进来都会new 创建此实例。
* 这种单例相对于每个线程来说确实是唯一的
*/
public class MoreSafe_singleton {

private static MoreSafe_singleton singleton = new MoreSafe_singleton();

public static MoreSafe_singleton getInstance(){
return singleton;
}
}
/** *//**
* @author lx
* volatile 这个只在JDK1.5以上出现 它确保singleton变量被初始化时,多个线程正确地处理singleton变量
* 这种写法如果性能是关注的重点,那么可以大大减少getInstance()的时间消耗
*/
public class VerySafe_singleton {

private volatile static VerySafe_singleton singleton;
private VerySafe_singleton(){}

public static VerySafe_singleton getInstance(){
if(singleton==null){
synchronized(VerySafe_singleton.class){
if(singleton==null){ //里面为何在加上判断是否为空?
//因为试想如果有三个线程其中一个线程刚刚走出synchronized块,这个时候又进来一个线程,
//如果不判断是否为空,这个又会实例一个变量那么就不是单例了
singleton=new VerySafe_singleton();
}
}
}
return singleton;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值