double check与staitc单例

来源:互联网 发布:java 定义var 编辑:程序博客网 时间:2024/06/06 04:18

今天一同事问double check是什么,

写了一人完整实例,代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace ConsoleApplication1
  5. {
  6.     public class OrderState
  7.     {
  8.         private OrderState() { }
  9.         private string ff;
  10.         private static OrderState singleton;
  11.         private static object syncObj = new object();
  12.         private static OrderState singleton2 = new OrderState();//相当于static OrderState()中创建
  13.         static OrderState()
  14.         {
  15.             //此处线程安全,类对象生的时间调用,static构造是由vm保证其线程安全
  16.             //这也是为什么static构造function没有private的原因,因为只能中private
  17.             //singleton2 = new OrderState();//由vm保证不同时,且只执行一次
  18.         }
  19.         public static OrderState GetSingleton2()
  20.         {
  21.             return singleton2;
  22.         }
  23.         public string FF
  24.         {
  25.             get { return this.ff; }
  26.             set { this.ff = value; }
  27.         }
  28.         public static OrderState GetSingleton()
  29.         {
  30.             //以下代码同时调用则会执行两次,(则两个实例,但结果不会问题,最后一个有效)    
  31.             if (singleton == null)
  32.             {
  33.                 lock (syncObj)
  34.                 {
  35.                     //lock中代码也会执行两次,但不会同时;
  36.                     if (singleton == null)//再次检查,即double check(仔细检查,多次检查)
  37.                     {
  38.                         singleton = new OrderState();//lock保证不同时,singleton != null保证只执行一次
  39.                     }
  40.                 }
  41.             }
  42.             return singleton;
  43.             //也可如下代码,但读操作也不能同步,不使用double check
  44.             //lock (syncObj)
  45.             //{
  46.             //    if (singleton == null)
  47.             //    {
  48.             //        singleton = new OrderState();//lock保证不同时,singleton != null保证只执行一次
  49.             //    }
  50.             //}
  51.         }
  52.     }
  53.     public class Test
  54.     {
  55.         public static void Main(string[] args)
  56.         {
  57.             OrderState test = OrderState.GetSingleton();
  58.             test.FF = "111";
  59.             OrderState test2 = OrderState.GetSingleton();
  60.             Console.WriteLine(test2.FF);
  61.             OrderState test3 = OrderState.GetSingleton2();
  62.             test3.FF = "222";
  63.             OrderState test4 = OrderState.GetSingleton2();
  64.             Console.WriteLine(test4.FF);
  65.             //GetSingleton单例的创建时间是由自已来决定的... 
  66.             //GetSingleton2,自已不会确定,由vm创建,用就好了,.由vm保证不同时,且只执行一次
  67.             //这是对象的生 
  68.             //对象的死是相同的,这是由类的staitic数据来决定的 
  69.             //GetSingleton的死是类死的时才死,而类什么时死,由.net决定(GC回收时,内存不够时),你不能确定 
  70.             //GetSingleton2的死是也类死的时才死,也是如此
  71.         }
  72.     }
原创粉丝点击