单例模式详解

单例模式是设计模式中比较常用的,今天我要详细的了解一下,并且进行一些比较

public class Singleton {

    //线程不安全,当多线程的时候可能有多个线程进入if(instance == null)的判断中
    private static Singleton instance = null;
    //私有化构造函数,这就保证了对象不能被new出来
    private Singleton (){

    }
    public static Singleton getInstance(){
        if(instance == null){
        //为了测试效果明显,让线程有时间进来
        try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        //单例模式的精髓就在这,类的内部可以new
            instance = new Singleton();
        }
        return instance;
    }

    //对这种写法的多线程的不安全的测试
    public static void main(String[] args) {    
        Thread thread1 = new Thread(){
            public void run() {
                System.out.println(getInstance().hashCode());
            };
        };
        Thread thread2 =new Thread(){
            public void run() {
                System.out.println(getInstance().hashCode());
            };
        };

        thread1.start();
        thread2.start();

    }
}

按照单例模式,每个类只有一个对象,就是hashcode应该是一样的。结果却是不一致,这样的单例模式在多线程下是不对的。

21281040
12271841

解决真个问题最直接的方法就是同步(synchronized)

public static synchronized Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
public static Singleton getInstance(){
        synchronized (Singleton.class) {
            if(instance == null){
                instance = new Singleton();
            }           
        }
        return instance;
    }

这两种方法其实差不多,都是在调用getInstance()进行同步,加锁。可以解决多线程下的安全性,但是每次调用getInstance()方法就会加锁解锁,是不是效率太低呢,下面通过两层判断来提高效率

public static Singleton getInstance(){
        //第一层判断就可以排除绝大多数调用
        if(instance == null){
        //在多线程的情况下,一开始可能有多个instance = null的情况进来
        synchronized (Singleton.class) {
            if(instance == null){
                instance = new Singleton();
            }           
          }
        }
        return instance;
    }

上面的模式俗称懒汉式,调用getInstance()才会创建对象。
下面的是饿汉式,在类创建的同时就已经创建好一个静态的对象。

//饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的
public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance() {
        return instance;
    }
}

通过静态内部类的方式,实现线程安全。

public class Singleton {
    private Singleton() {
    }
    public static Singleton getInstance() {
        return InstanceHolder.instance;
    }
    //静态内部类只会被加载一次
    static class InstanceHolder{
        private static Singleton instance = new Singleton();
    }
}

这几种基本就是单例常用的方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值