zoukankan      html  css  js  c++  java
  • 单件模式 多线程

    2010-8-19,做了个多线程的案例。有单件模式的多线程(方法:InstanceSingleTon)和计数的多线程(方法:Count)。
    代码比较简单,主要是code单件模式,多线程同步,异步的概念。
    贴代码如下:
     class Program
        {
            static void Main(string[] args)
            {
     
                Thread[] threads = new Thread[10];
     
                for (int i = 0; i < 10; i++)
                {
                    threads[i] = new Thread(new ThreadStart(SingleTon.Count));
                }
     
                foreach (Thread t in threads)
                {
                    t.Start();
                }
     
                Console.ReadLine();
            }
        }
     

        public class SingleTon
        {
            static int intIn = 0;
     
            public static SingleTon instance;
            private static object lockHelper = new object();
     
            private SingleTon()
            {
               
            }
     
            /// <summary>
            ///  计数。注释的lock代码是锁对象,实现多线程-同步操作。目的:按顺序显示索引值。1,2,3,4,5,6,7,8,9,10
            /// 现在的代码是多线程-异步操作。
            /// </summary>
            public static void Count()
            {
                //lock (lockHelper)
                //{
                //    Console.WriteLine("Current:" + Convert.ToString(++intIn));
                //}
     
                Console.WriteLine("Current:" + Convert.ToString(++intIn));
              
            }
     
            /// <summary>
            /// 单件模式,防止多线程-同步实例化
            /// </summary>
            /// <returns></returns>
            public static SingleTon InstanceSingleTon()
            {
                if (instance == null)
                {
                    lock (lockHelper)
                    {
                        if (instance==null)
                        {
                            instance = new SingleTon();
                        }
                    }
                }
                return instance;
            }
        }
  • 相关阅读:
    Python3基础 函数 未指定返回值,返回NONE
    Python3基础 函数 有参数有返回值 对传入的参数加1
    Python3基础 函数 无参数无返回值 调用会输出hello world的函数
    Python3基础 函数 收集参数(tuple)+普通参数 的示例
    MVC中几种常用ActionResult
    sqlserver 中存储过程的基础知识记录
    常用的正则表达式方法2
    常用的正则表达式方法1
    vs2012运行项目报未能加载文件或程序集“System.Web.Mvc, Version=4.0.0.1,Culture=neutral”问题和解决方法
    怎样解决PowerDesigner15出现许可证过期问题?
  • 原文地址:https://www.cnblogs.com/chinaagan/p/singleton.html
Copyright © 2011-2022 走看看