public static Singleton Value{
get {
// Has the singleton object already been created?
if (s_value == null) {
// No, only one thread should create it
lock (s_lock) {
// Did another thread create it?
if (s_value == null) {
// No, OK, this thread will create it.
// Volatile ensures that all of singleton object's fields
// (initialled by the constructor) are flushed before
// other threads see the reference to the Singleton object
s_value = new Singleton();
}
}
第二次檢查是因爲如果兩個線程都進入了 if (s_value == null) {,一個線程lock住new完了以後,另一個線程又lock並new,把原來的實例沖掉了