示例代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Incorrect Counter");
Counter c1 = new Counter();
var t1 = new Thread(() => TestCounter(c1)); //派生类等与实例化后的基类,c1 is CounterBase
var t2 = new Thread(() => TestCounter(c1));
var t3 = new Thread(() => TestCounter(c1));
t1.Start();
t2.Start();
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("Total Count:{0}", c1.Count);
Console.WriteLine("------------------------");
Console.WriteLine("Correct counter");
CounterWithLock c2 = new CounterWithLock();
t1 = new Thread(() => TestCounter(c2)); //派生类等与实例化后的基类,c2 is CounterBase
t2 = new Thread(() => TestCounter(c2));
t3 = new Thread(() => TestCounter(c2));
t1.Start();
t2.Start();
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("Total Count:{0}", c2.Count);
}
static void TestCounter(CounterBase c)
{
for(int i=0;i<10000;i++)
{
c.Increment(); //增量
c.Decrement(); //减量
}
}
class Counter : CounterBase
{
public int Count { get; private set; } //计算后的结果
public override void Decrement() //对定义的抽象方法重写
{
Count--;
}
public override void Increment()
{
Count++;
}
}
class CounterWithLock : CounterBase
{
private readonly object _asyncRoot = new object();
public int Count { get; private set; }
public override void Decrement()
{
lock (_asyncRoot) //这里也可以把全局静态变量_asyncRoot改成this
{
Count--;
}
}
public override void Increment()
{
lock(_asyncRoot)
{
Count++;
}
}
}
abstract class CounterBase
{
public abstract void Increment(); //增量函数
public abstract void Decrement(); //减量函数
}
}