zoukankan      html  css  js  c++  java
  • C#单例模式的2种实现方式,Lazy模式和双检锁模式

     1     public class MyClass
     2     {
     3         //volatile 关键字指示一个字段可以由多同时执行的线程修改。 声明为 volatile 的字段不受编译器优化(假定由单个线程访问)的限制。 这样可以确保该字段在任何时间呈现的都是最新的值。
     4         private static volatile MyClass _instance;
     5         private static readonly object InstanceLock = new object();
     6         public static MyClass Instance
     7         {
     8             get
     9             {
    10                 if (_instance == null)
    11                 {
    12                     lock (InstanceLock)
    13                     {
    14                         if (_instance != null)
    15                         {
    16                             return _instance;
    17                         }
    18                         _instance = new MyClass();
    19                     }
    20                 }
    21 
    22                 return _instance;
    23             }
    24         }
    25 
    26         //在.NET 中这种模式已用 Lazy<T>类实现了封装,内部就是使用了双检锁模式。 你最好还是使用 Lazy<T>,不要去实现自己的双检锁模式了。这样非常的简洁
    27         public static MyClass Instance2 = new Lazy<MyClass>(() => new MyClass()).Value;
    28     }
    29 
    30     class Program
    31     {
    32 
    33 
    34         static void Main(string[] args)
    35         {
    36             for (int i = 0; i < 10; i++)
    37             {
    38                 Thread th = new Thread(() => { Console.WriteLine("线程调用对象{0}", MyClass.Instance.GetHashCode()); });
    39                 th.Start();
    40             }
    41             for (int i = 0; i < 10; i++)
    42             {
    43                 Thread th = new Thread(() => { Console.WriteLine("线程调用对象{0}", MyClass.Instance2.GetHashCode()); });
    44                 th.Start();
    45             }
    46 
    47             Console.ReadLine();
    48         }
    49 
    50     }

    打印出的结果

  • 相关阅读:
    解惑开源项目协作流程
    结合webpack 一步一步实现懒加载的国际化简易版方案
    SEO优化之——hreflang(多语言网站优化)
    pandas数据分析常用
    多任务: 多进程与多线程
    linux基础知识
    python常用模块之sys, os, random
    递归函数(初级难点)
    内置函数
    函数
  • 原文地址:https://www.cnblogs.com/zsx-blog/p/13792360.html
Copyright © 2011-2022 走看看