单例模式还不会。。。
饿汉
public class S {
private static S ex=new S();
private S(){
}
private static S getEx(){
return ex;
}
public static void main(String[] args) {
System.out.println(ex);
}
}
懒汉
public class S2 {
private static S2 ex;
private S2(){
}
public static synchronized S2 getEx(){
if(ex==null){
ex= new S2();
}
return ex;
}
public static void main(String[] args) {
System.out.println(ex);
}
}
双重锁
class S{
private volatile static S ex=null;
private S(){}
public static S getEx(){
if(ex == null){
synchronized(S.class){
if(ex == null)
ex = new S(); //创建实例
}
}
return ex;
}
}