每每面试,单例必问,但是,每次都答的不好?额,可能是太简单了,一看就会,平时单例场景 也很少接触。 以为 掌握了,一到问的细节的时候,就不行了。
public class SingletonTest {
// 必须是静态属性, volatile 是为了防止 指令重排序,必须初始化后才将地址赋值给指针
// 比如,指针赋值后,还没初始化,其他线程 判断指针不为null,则使用,会出问题
private volatile static SingletonTest instance;
private SingletonTest(){
}
// 必须是静态方法
public static SingletonTest getInstance(){
if (instance == null){
synchronized (SingletonTest.class){
if (instance == null){
instance = new SingletonTest();
}
}
}
return instance;
}
public void m1(){
}
}
public class SingletonTest {
private SingletonTest(){
}
/**
* 内部类,在外部类加载时,不会被加载。
* 只有使用了 内部类的成员变量或方法时,才加载。
*/
static class SingletonHolder {
private static SingletonTest INSTANCE = new SingletonTest();
}
public static SingletonTest getInstance(){
return SingletonHolder.INSTANCE;
}
public void m1(){
}
}