public class singletonTest {
/* 懒汉式 多线程下不安全 */
private singletonTest(){}
private static singletonTest instance;
public static singletonTest getInstance(){
if(instance==null){
instance=new singletonTest();
}
return instance;
}
/* 懒汉式 多线程下安全性较高 */
private singletonTest(){}
private static singletonTest instance;
public synchronized static singletonTest getInstance(){
if(instance==null){
instance=new singletonTest();
}
return instance;
}
/* 恶汉式*/
private singletonTest(){}
private static singletonTest instance=new singletonTest();
public static singletonTest getInstance(){
return instance;
}
/*双重检验锁*/
private singletonTest(){}
private static singletonTest instance;
public static singletonTest getInstance(){
if(instance==null){
synchronized (singletonTest.class) {
if(instance==null){
instance=new singletonTest();
}
}
}
return instance;
}
/* 双重检验锁优化 因为编译器中存在指令重排序的问题 注意java5之前无效*/
private singletonTest(){}
private volatile static singletonTest instance;
public static singletonTest getInstance(){
if(instance==null){
synchronized (singletonTest.class) {
if(instance==null){
instance=new singletonTest();
}
}
}
return instance;
}
/*静态类部类*/
private singletonTest(){}
private static class getSingletonTestHolder{
private static singletonTest instatce=new singletonTest();
}
public static final singletonTest getInstance(){
return getSingletonTestHolder.instatce;
}
/*枚举*/
public enum EasySingleton{
INSTANCE;
}
}
这么多,你都看到这里了,果然是真爱啊!!!!!