(接上部分)
以下为 Main 函数,本程序的测试入口:
using System;
namespace csPattern.Singleton
{
public class RunMain
{
public RunMain() {}
static public void Main (string[] args)
{
MutileThread.MutileClient myClient = new MutileThread.MutileClient();
myClient.ClientMain();
System.Console.ReadLine();
}
}
}
执行结果如下:
线程 Thread 1 报告 : 当前 counter 为 : 2
线程 Thread 1 报告 : 当前 counter 为 : 4
线程 Thread 1 报告 : 当前 counter 为 : 5
线程 Thread 1 报告 : 当前 counter 为 : 6
线程 Thread 3 报告 : 当前 counter 为 : 7
线程 Thread 3 报告 : 当前 counter 为 : 8
线程 Thread 3 报告 : 当前 counter 为 : 9
线程 Thread 3 报告 : 当前 counter 为 : 10
线程 Thread 0 报告 : 当前 counter 为 : 1
线程 Thread 0 报告 : 当前 counter 为 : 11
线程 Thread 0 报告 : 当前 counter 为 : 12
线程 Thread 0 报告 : 当前 counter 为 : 13
线程 Thread 2 报告 : 当前 counter 为 : 3
线程 Thread 2 报告 : 当前 counter 为 : 14
线程 Thread 2 报告 : 当前 counter 为 : 15
线程 Thread 2 报告 : 当前 counter 为 : 16
由于系统线程调度的不同,每次的执行结果也不同,但是最终结果一定是 16 。
方法一中由于实例一开始就被创建,所以 instance() 方法无需再去判断是否已经存在唯一的实例,而返回该实例,所以不会出现计数器类多次实例化的问题。
使用方法二:
using System;
using System.Threading;
using System.Runtime.CompilerServices;
namespace csPattern.Singleton
{
public class Counter_lazy
{
static Counter_lazy uniCounter;
private int totNum = 0;
private Counter_lazy()
{
Thread.Sleep(100); // 假设多线程的时候因某种原因阻塞 100 毫秒
}
[MethodImpl(MethodImplOptions.Synchronized)] // 方法的同步属性
static public Counter_lazy instance()
{
if (null == uniCounter)
{
uniCounter = new Counter_lazy();
}
return uniCounter;
}
public void Inc() { totNum ++;}
public int GetCounter() { return totNum;}
}
}
不知道大家有没有注意到 instance() 方法上方的 [MethodImpl(MethodImplOptions.Synchronized)] 语句,他就是同步的要点,他指定了 instance() 方法同时只能被一个线程使用,这样就避免了线程 0 调用 instance() 创建完成实例前线程 1 就来调用 instance() 试图获得该实例。
根据 MSDN 的提示,也可以使用 lock 关键字进行线程的加锁,代码如下:
using System;
using System.Threading;
namespace csPattern.Singleton
{
public class Counter_lazy
{
static Counter_lazy uniCounter;
static object myObject = new object();
private int totNum = 0;
private Counter_lazy()
{
Thread.Sleep(100); // 假设多线程的时候因某种原因阻塞 100 毫秒
}
static public Counter_lazy instance()
{
lock(myObject)
{
if (null == uniCounter)
{
uniCounter = new Counter_lazy();
}
return uniCounter;
}
}
public void Inc() { totNum ++;}
public int GetCounter() { return totNum;}
}
}
lock() 是对一个对象加互斥锁,只允许一个线程访问其后大括号中语句块,直到该语句块的代码执行完才解锁,解锁后才允许其他的线程执行其语句块。
还可以使用 Mutex 类进行同步,定义 private static Mutex mut = new Mutex(); 后,修改 instance() 如下,同样可以得到正确的结果:
static public Counter_lazy instance()
{
mut.WaitOne();
if (null == uniCounter)
{
uniCounter = new Counter_lazy();
}
mut.ReleaseMutex();
return uniCounter;
}
注意的是,本例中使用方法二要更改方法一的客户程序,去掉 Counter_lazy.intance() 的注释,并将 Counter.intance() 注释。
singleton 模式还可以拓展,只要稍加修改,就可以限制在某个应用中只能允许 m 个实例存在,而且为 m 个实例提供全局透明的访问方法。