餓漢式 static 初始化:線程安全
- 餓漢模式的另一種寫法:使用靜態代碼塊。
- 注意:使用靜態代碼段static{} 初始化單例對象時,一定要注意靜態代碼段的單例對象申明語句的順序,類加載時,是順序執行的。圖中的靜態變量聲明一定要放在靜態代碼塊前面。
正確代碼
package com.mmall.concurrency.example.singleton;
import com.mmall.concurrency.annoations.ThreadSafe;
/**
* 餓漢模式
* 單例實例在類裝載時進行創建
*/
@ThreadSafe
public class SingletonExample6 {
// 私有構造函數
private SingletonExample6() {
}
// 單例對象
private static SingletonExample6 instance = null;
static {
instance = new SingletonExample6();
}
// 靜態的工廠方法
public static SingletonExample6 getInstance() {
return instance;
}
public static void main(String[] args) {
System.out.println(getInstance().hashCode());
System.out.println(getInstance().hashCode());
}
}