标签:style blog http color os 使用 java ar strong
参加一个面试,被问到多线程下的单例模式会创建几个对象,总结一下:
首先我的单例是这么写的(懒汉式)
public class Singleton{
private static Singleton singleton;
private Singleton(){}
public Singleton getInstance(){
if(singleton == null){
singleton = new singleton();
}
return singleton;
}
} 这样写的话,
当线程A访问到 getInstance() 时候, singleton 为 null,
此时线程B也访问到 getInstance(), singleton 也为 null,
然后必然就创建俩个对象了,问题出现了。。
然后想到线程同步synchronized,可是这样必然会有效率问题。
google之。。。
发现如下方法:
私有的静态内部类,当不调用getInstance()方法时,就不会调用这个内部类,就不会产生实例。
没有使用锁,没有产生无用的实例。确实是最好的方法。
public class SingletonTest
{
private SingletonTest(){}
private static class Inner{ //私有的静态内部类
static SingletonTest singletonTest = new SingletonTest();
}
public static SingletonTest getInstance(){
return Inner.singletonTest;
}
}
参考大神文章:http://770736680.iteye.com/blog/2036707
标签:style blog http color os 使用 java ar strong
原文地址:http://my.oschina.net/igeeker/blog/314925