(一)System.Threading.Interlocked类为多个线程共享的变量提供原子操作。
为整型类提供原子类操作
经验显示,那些需要在多线程情况下被保护的资源通常是整型值,且这些整型值在多线程下最常见的操作就是递增、递减或相加操作。Interlocked类提供了一个专门的机制用于完成这些特定的操作。这个类提供了Increment、Decrement、Add静态方法用于对int或long型变量的递增、递减或相加操作。
(二)控制台代码显示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication7
{
class Program
{
static int counter = 1;
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(F1));
Thread t2 = new Thread(new ThreadStart(F2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.ReadLine();
}
static void F1()
{
for (int i = 1; i < 6; i++)
{
Interlocked.Increment(ref counter);
Console.WriteLine("Counter++:{0}", counter);
Thread.Sleep(20);
}
}
static void F2()
{
for (int i = 1; i < 6; i++)
{
Interlocked.Decrement(ref counter);
Console.WriteLine("Counter--:{0}", counter);
Thread.Sleep(20);
}
}
}
}
(三)小结
Interlocked类还提供了Exchange(为整型或引用对象赋值)、CompareExchange(比较后再对整型或引用对象赋值),用于为整型或引用类型的赋值提供原子操作。