您的位置:首页 > 职场人生

【JAVA面试题】设计单例模式的多线程实现

2015-04-30 17:01 441 查看
[b]在阅读的过程中有任何问题,欢迎一起交流[/b]

邮箱:1494713801@qq.com
QQ:1494713801

单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点,可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制,“阻止”所有想要生成对象的访问。使用工厂方法来限制实例化过程。这个方法应该是静态方法(类方法),因为让类的实例去生成另一个唯一实例毫无意义。



[align=left] [/align]
代码如下:

[java]

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

以下代码既可以保证线程安全又可以提高多线程并发的效率。

[java]

public class Singleton {
private static Singleton uniqueInstance = null;

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

或者这么写:

[java]

public class Singleton {
private static Singleton uniqueInstance = null;

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

参考链接:http://blog.csdn.net/mrfly/article/details/13372441
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐