罗马人凯撒大帝,威震欧亚非三大陆,临终告诉侍者说:“请把我的双手放在棺材外面,让世人看看,伟大如我凯撒者,死后也是两手空空。
ICounter.cs类:
interface ICounter
{
void Increment();
void Decrement();
}
Counter.cs类:
class Counter : ICounter
{
private int _count = 0;
public int Count { get { return _count; } }
public void Increment()
{
_count ++;
}
public void Decrement()
{
_count--;
}
}
CounterLock.cs代码:
class CounterLock : ICounter
{
private int _count;
public int Count { get { return _count; } }
public void Increment()
{
Interlocked.Increment(ref _count);
}
public void Decrement()
{
Interlocked.Decrement(ref _count);
}
}
Test.cs代码:
class Test
{
public static void TestCounter(ICounter c)
{
for (int i = 0; i < 100000; i ++)
{
c.Increment();
c.Decrement();
}
}
public static void RunTest()
{
var c1 = new Counter();
var t1 = new Thread((() => TestCounter(c1)));
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("总数: {0}", c1.Count);
Console.WriteLine("--------------------------");
Console.WriteLine("普通计数器");
Console.WriteLine("");
var c2 = new CounterLock();
t1 = new Thread((() => TestCounter(c2)));
t2 = new Thread((() => TestCounter(c2)));
t3 = new Thread((() => TestCounter(c2)));
t1.Start();
t2.Start();
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("总数: {0}", c2.Count);
Console.WriteLine("--------------------------");
Console.WriteLine("线程同步的计数器");
Console.ReadKey();
}
}
运行结果如图: