標籤:ret turn track div 運行 oid atom main zab
我們學習java時,通常被告知,變數定義的順序不重要,可是下面程式確在jdk 1.7上執行出錯。
public class FactoryImpl implements Serializable { private final static FactoryImpl INSTANCE = new FactoryImpl(); private final static AtomicInteger count = new AtomicInteger(0); private int id; private FactoryImpl() { id = count.incrementAndGet(); } public int getId() { return id; } public static FactoryImpl getInstance() { return INSTANCE; } public static void main(String[] args) { FactoryImpl impl1 = FactoryImpl.getInstance(); System.out.println(impl1.id); }}
把下面代碼調整順序之後能夠運行成功。
private static final FactoryImpl INSTANCE = new FactoryImpl(); private final static AtomicInteger count = new AtomicInteger(0);
原因例如以下,假設不調整時,當類被載入時,先初始化INSTANCE靜態變數,這時,會調用FactoryImpl構造方法,在此構造方法裡,調用count.incremnetAndGet();這時count還沒有初始化。這是因為進行類載入時。靜成變數的初始化順序造成的。
java語句順序有時非常重要