正文

单件模式例子2007-11-10 12:44:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/jixian/30847.html

分享到:

转自http://terrylee.cnblogs.com/archive/2005/12/09/293509.html

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace SingletonCounter
{
    ///<summary>
    ///功能:简单计数器的单件模式
    ///编写:XXX
    ///日期:2007年11月10日
    ///</summary>

    public class CounterSingleton
    {
        ///存储唯一的实例
        static CounterSingleton uniCounter = new CounterSingleton();

        ///存储计数值
        private int totNum = 0;

        private CounterSingleton()
        {
            ///线程延迟2000毫秒
            Thread.Sleep(2000);
        }

        static public CounterSingleton Instance()
        {
            return uniCounter;
        }


        /// 计数加1
        public void Add()
        {
            totNum ++;
        }
        ///获取当前计数值
        public int GetCounter()
        {
            return totNum;
        }

    }

    /// <summary>
    /// 功能:创建一个多线程计数的类
    /// 编写:XXX
    /// 日期:2007年11月1日
    /// </summary>
   
    public class CountMutilThread
    {
        public CountMutilThread()
        {

        }

        ///线程工作
        public static void DoSomeWork()
        {
            string results = "";
            CounterSingleton MyCounter = CounterSingleton.Instance();
           
            ///循环调用四次
            for (int i = 1; i < 5; i++)
            {
                ///开始计数
                MyCounter.Add();
                results += "线程";
                results += Thread.CurrentThread.Name.ToString() + "---->  ";
                results += "当前的计数: ";
                results += MyCounter.GetCounter().ToString();
                results += "\n";
                Console.WriteLine(results);
                results = "";
            }
        }

        public void StartMain()
        {
            Thread thread0 = Thread.CurrentThread;
            thread0.Name = "Thread0";

            Thread thread1 = new Thread(new ThreadStart(DoSomeWork));
            thread1.Name = "Thread1";

            Thread thread2 = new Thread(new ThreadStart(DoSomeWork));
            thread2.Name = "Thread1";

            Thread thread3 = new Thread(new ThreadStart(DoSomeWork));
            thread3.Name = "Thread1";

            thread1.Start();
            thread2.Start();
            thread3.Start();

            //线程0也执行和其它线程相同的工作
            DoSomeWork();
        }
    }

    /// <summary>
    /// 功能:实现多线程计数器的客户端
    /// 编写:XXX
    /// 日期:2007年11月10日
    /// </summary>
    public class CounteClient
    {
        public static void Main(string[] args)
        {
            CountMutilThread cmt = new CountMutilThread();
            cmt.StartMain();
            Console.ReadLine();
        }
    }
}

阅读(2249) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册