转自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(); } }}

评论