码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式(Singleton)的同步锁synchronized

时间:2017-11-02 21:09:15      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:clock   instance   线程安全   single   程序   final   tin   param   get   

单例模式,有“懒汉式”和“饿汉式”两种。

懒汉式

单例类的实例在第一次被引用时候才被初始化。

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

饿汉式

单例类的实例在加载的时候就被初始化。

public class Singleton {  
    private static Singleton instance = new Singleton();  
     
    private Singleton() {  
         
    }  
     
    public static Singleton getInstance(){  
        return instance;  
    }  
}

在单线程程序中,上面两种形式基本可以满足要求了,但是在多线程环境下,单例类就有可能会失效,这个时候就要对其加锁了,来确保线程安全。

对线程加锁用的synchronized关键字,这个关键字的用法主要也分为两种:

一种是加在方法名之前,形如:synchronized methodeName(params){……};

二是声明同步块,形如:synchronized(this){……};

下面是对懒汉式单例类加上线程同步的实现:

同步方法:

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

这种方式效率比较低,性能不是太好,不过也可以用,因为是对整个方法加上了线程同步,其实只要在new的时候考虑线程同步就行了,这种方法不推荐使用。

同步代码块:

public class Singleton {  
    private static Singleton instance;  
    private final static Object syncLock = new Object();  
     
    private Singleton() {  
         
    }  
     
    public static Singleton getInstance(){  
        if (instance == null) {  
            synchronized (syncLock) {  
                if (instance == null) {  
                    instance = new Singleton();  
                }  
            }  
        }  
         
        return instance;  
    }  
}

synchronized同步块括号中的锁定对象是采用的一个无关的Object类实例,而不是采用this,因为getInstance是一个静态方法,在它内部不能使用未静态的或者未实例的类对象,因此也可以用下面的方法来实现:

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

单例模式(Singleton)的同步锁synchronized

标签:clock   instance   线程安全   single   程序   final   tin   param   get   

原文地址:http://www.cnblogs.com/qq895139140/p/7774152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!