单例模式中静态变量初始化与不初始化有什么区别

public class Singleton { 
	private static Singleton obj = new Singleton(); 
	public static int counter1; 
	public static int counter2 = 0; 
	private Singleton(){ 
		counter1++; 
		counter2++; 
	} 

	public static Singleton getInstance(){ 
		return obj; 
	} 

	public static void main(String[] args) { 

		Singleton obj = Singleton.getInstance(); 
		System.out.println("obj.counter1: " + obj.counter1); 
		System.out.println("obj.counter2: " + obj.counter2); 
	} 

} 
这个和Java初始化顺序有关, 
由于你的第一句是 
private static Singleton obj = new Singleton(); 
所以在初始化静态变量obj时中间插入了一个构造函数,造成了counter1和counter2最后的结果不一样。完整的时间链如下 

1) JVM调用Singleton.Main,由于这是一个static method,JVM必须构造Singleton的所有static member,按照Java Specifiction的要求,指针被初始化为null,数值为0。到此为止 counter1=0,counter2=0 

2)接下来,按照自上而下的顺序,完成所有static member的赋值操作。第一个赋值操作是(static)obj = new Singleton() ,JVM会调用Singleton的构造函数,完成counter1和counter2的赋值。到此为止 counter1=1,counter2=1 

3)接着执行的是rivate static Singleton obj = new Singleton();的下一句(public static int)counter2 = 0;到此为止 counter1=1,counter2=0 


你可以试试把private static Singleton obj = new Singleton();放到最后,则结果就都是1了。 

另外说一句,你这个所谓单例的用法是不正确的。既然已经把Singleton设为单例,counter1和counter2也就没有必要设为static,这样由于static member会在non static member面前被初始化,自然就没有这个问题了。同时由于Singleton被设为了单例,也不用担心把counter1和counter2前面的static去掉会造成空间方面的浪费。

你可能感兴趣的:(JAVA)