给出两种单例模式的实现方法,并说明这两种方法的优缺点
写法一:
public class Test {
private static Test test = new Test();
public Test(){};
public static Test getInstance(){
return test;
}
}
写法二:
public class Test {
private static Test test = null;
private Test(){};
public static Test getInstance(){
if (test==null) {
test = new Test();
}
return test;
}
}
对于第一种写法,当类被加载的时候,已经创建好了一个静态的对象,因此,是线程安全的,但缺点是在这个对象还没有被使用的时候就已经被创建出来了。
对于第二种写法,缺点如下:这种写法不是线程安全的,例如当第一个线程执行判断语句 if(test==null)时,第二个线程执行判断语句 if(test==null),接着第一个线程执行语句test = new Test(),第二个线程也执行语句
test = new Test(),在这种多线程环境下,可能会创建出两个对象。当然,这种写法的优点是按需创建对象,只有对象使用的时候才会被创建。