using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace 多线程LOCK.InterLock
{//打印机:有三台计算机同事发出打印指令,使用Exchange实现锁
class Program
{
class Printerwithinterlocktest
{
public static int computernum = 3;//计算机数量
public static void openthread()
{
Thread thread;
Random random = new Random();
thread = new Thread(printerproc);
thread.Name = "mythread";
thread.Start();
}
private static void printerproc()
{
userprint();
Thread.Sleep(1000);
}
public static int usingprint = 0;//初始化正在打印状态
private static bool userprint()
{
if ( Interlocked.Exchange(ref usingprint, 1) ==0)
{
int c = 1;
Console.WriteLine(Thread.CurrentThread.Name + "acquired the lock");
Thread.Sleep(5000);
Console.WriteLine(Thread.CurrentThread.Name + "existed the lock");
Interlocked.Exchange(ref usingprint, 0);
return true;
}
else
{
int c = 2;
Console.WriteLine(Thread.CurrentThread.Name + "is denited the lock");
return false;
}
}
}
static void Main(string[] args)
{
Printerwithinterlocktest.openthread();
Console.ReadKey();
}
}
}
这段代码在执行到if ( Interlocked.Exchange(ref usingprint, 1) ==0)时,按照调试结果看是继续执行而不是跳入到Else,想问问到底是先执行Exchange方法还是先比较呢,为什么
运行结果