单例模式线程安全问题
饿汉式:
package com.atjava.test;
public class Single {
private static Single single;
private Single(){
}
public static Single getSingle() {
return single;
}
}
懒汉式:
package com.atjava.test;
public class SingleHungry {
private static SingleHungry singleHungry = null;
private SingleHungry(){
}
public static SingleHungry getSingleHungry() {
if(singleHungry == null){
synchronized (SingleHungry.class){
if(singleHungry == null){
singleHungry = new SingleHungry();
}
}
}
return singleHungry;
}
}
声明为静态的可以通过类直接调用,实例对象是private,构造方法是private,这样其他类不能直接创建实例对象必须通过getInstace方法
浙公网安备 33010602011771号