今天一同事问double check是什么,
写了一人完整实例,代码如下:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleApplication1
- {
- public class OrderState
- {
- private OrderState() { }
- private string ff;
- private static OrderState singleton;
- private static object syncObj = new object();
- private static OrderState singleton2 = new OrderState();//相当于static OrderState()中创建
- static OrderState()
- {
- //此处线程安全,类对象生的时间调用,static构造是由vm保证其线程安全
- //这也是为什么static构造function没有private的原因,因为只能中private
- //singleton2 = new OrderState();//由vm保证不同时,且只执行一次
- }
- public static OrderState GetSingleton2()
- {
- return singleton2;
- }
- public string FF
- {
- get { return this.ff; }
- set { this.ff = value; }
- }
- public static OrderState GetSingleton()
- {
- //以下代码同时调用则会执行两次,(则两个实例,但结果不会问题,最后一个有效)
- if (singleton == null)
- {
- lock (syncObj)
- {
- //lock中代码也会执行两次,但不会同时;
- if (singleton == null)//再次检查,即double check(仔细检查,多次检查)
- {
- singleton = new OrderState();//lock保证不同时,singleton != null保证只执行一次
- }
- }
- }
- return singleton;
- //也可如下代码,但读操作也不能同步,不使用double check
- //lock (syncObj)
- //{
- // if (singleton == null)
- // {
- // singleton = new OrderState();//lock保证不同时,singleton != null保证只执行一次
- // }
- //}
- }
- }
- public class Test
- {
- public static void Main(string[] args)
- {
- OrderState test = OrderState.GetSingleton();
- test.FF = "111";
- OrderState test2 = OrderState.GetSingleton();
- Console.WriteLine(test2.FF);
- OrderState test3 = OrderState.GetSingleton2();
- test3.FF = "222";
- OrderState test4 = OrderState.GetSingleton2();
- Console.WriteLine(test4.FF);
- //GetSingleton单例的创建时间是由自已来决定的...
- //GetSingleton2,自已不会确定,由vm创建,用就好了,.由vm保证不同时,且只执行一次
- //这是对象的生
- //对象的死是相同的,这是由类的staitic数据来决定的
- //GetSingleton的死是类死的时才死,而类什么时死,由.net决定(GC回收时,内存不够时),你不能确定
- //GetSingleton2的死是也类死的时才死,也是如此
- }
- }