多线程为什么要Double-Check Locking

来源:互联网 发布:链家端口费是按月扣吗 编辑:程序博客网 时间:2024/05/27 06:53

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,把原来的实例冲掉了

原创粉丝点击