2018-06-05
Java 五中简单的创建单例方法
1.线程不安全
public class SingleTest {
private static SingleTest single = null;
public static SingleTest getSingleTest(){
if(single == null){
single = new SingleTest();
}
return single;
}
}
2.同步锁
public class SingleTest {
private static SingleTest single = null;
public static synchronized SingleTest getSingleTest(){
if(single == null){
single = new SingleTest();
}
return single;
}
}
3.减少锁的范围
public class SingleTest {
private static SingleTest single = null;
public static SingleTest getSingleTest(){
if(single == null){
synchronized(this){
if(single == null){
single = new SingleTest();
}
}
}
return single;
}
}
4.静态初始化
public class SingleTest {
private static SingleTest single = null;
static {
single = new SingleTest();
}
public static SingleTest getSingleTest(){
return single;
}
}
5.静态内部类
public class SingleTest {
private static class SingleHolder {
private static SingleTest single = new SingleTest ();
}
public static SingleTest getSingleTest(){
return SingleHolder.single ;
}
}