Counter.cs:
class Counter
{
//存储唯一的实例
static Counter uniCounter = new Counter();
//存储计数值。
private int totNum = 0;
//用private访问修饰符是防止用new关键字来实例化本类
private Counter()
{
//这里假设因为某种因素而耽搁了100毫秒
Thread.Sleep(100);
}
static public Counter instance()
{
return uniCounter;
}
//计数加1
public void Inc()
{
totNum ++;
}
//获得当前计数值
public int GetCounter()
{
return totNum;
}
}
Couter的客户端程序:
class MutileClient
{
public MutileClient()
{
}
public void DoSomeWork()
{
Counter myCounter = Counter.instance();
for (int i = 1; i < 5; i++)
{
myCounter.Inc();
Console.WriteLine("线程{0}报告: 当前counter为: {1}", Thread.CurrentThread.Name.ToString(), myCounter.GetCounter().ToString());
}
}
public void ClientMain()
{
Thread thread0 = Thread.CurrentThread;
thread0.Name = "Thread 0";
Thread thread1 = new Thread(new ThreadStart(this.DoSomeWork));
thread1.Name = "Thread 1";
Thread thread2 = new Thread(new ThreadStart(this.DoSomeWork));
thread2.Name = "Thread 2";
Thread thread3 = new Thread(new ThreadStart(this.DoSomeWork));
thread3.Name = "Thread 3";
thread1.Start();
thread2.Start();
thread3.Start();
//线程0也只执行和其他线程相同的工作。
DoSomeWork();
}
}
测试类:
class App
{
public static void Main()
{
//测试有关Singleton方面的Counter
MutileClient myClient = new MutileClient();
myClient.ClientMain();
System.Console.ReadLine();
}
}