public class MyInterlockedExchangeExampleClass
private static int usingResource = 0;
private const int numThreadIterations = 5;
private const int numThreads = 10;
public static void Main()
Random rnd = new Random();
for(int i=0; i < numThreads; i++)
myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = string.Format("Thread{0}", i + 1);
Thread.Sleep(rnd.Next(0, 1000));
private static void MyThreadProc()
for(int i = 0; i < numThreadIterations; i++)
static bool UseResource()
if(0 == Interlocked.Exchange(ref usingResource, 1))
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
Interlocked.Exchange(ref usingResource, 0);
Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name);