Java線程安全單例模式

在寫單例模式時應該對實例的初始化與否進行雙重檢查。
記住對實例的聲明使用Volatile關鍵字,以保證單例模式是線程安全的


/**
 * Created by lufie on 2017/7/30.
 */
public class SingleInstance {

    public static volatile SingleInstance instance;

    private SingleInstance(){

    }

    public static SingleInstance getInstance(){
        if(instance==null){
            synchronized (SingleInstance.class){
                if(instance==null){
                    System.out.println("execute new method ...");
                    instance = new SingleInstance();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        SingleInstance instance = SingleInstance.getInstance();
        System.out.println(instance);
        instance = SingleInstance.getInstance();
        System.out.println(instance);
    }

}
相關文章
相關標籤/搜索