今天上操作系统的时,老师讲到进程同步提到售票系统,记得以前看孙鑫老师的视频时也提到过类似的东西。回来后马上动手,用C#实现了一个简单的进程同步。
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
using System.Threading;
public class ThreadCreat
{
static int tickets = 100; //没有全局变量,静态变量也一样
//为了使进程同步,需要一个监视器来阻止第二个线程进入一个受保护的代码段
readonly static object _Sync = new object();
public static void ThreadProc1()
{
// Interlocked.Decrement(ref tickets); //这里不知道是什么,网上提供的方法,但是没用
while (true)
{
Monitor.Enter(_Sync);
try
{
if (tickets > 0)
{
Thread.Sleep(1);
Console.WriteLine("thread 1 sell:titck leave {0} ", tickets--);
}
else
break;
}
finally
{
Monitor.Exit(_Sync);
}
}
}
public static void ThreadProc2()
{
while (true)
{
// Interlocked.Decrement(ref tickets);
Monitor.Enter(_Sync);
try
{
if (tickets > 0)
{
Thread.Sleep(1);
Console.WriteLine("thread 2 sell:titck leave {0} ", tickets--);
}
else
break;
}
finally
{
Monitor.Exit(_Sync);
}
}
}
public static void Main()
{
//这里使用的是C#2.0的委托推断语法,不是显示地实例化ThreadStart
Thread thread1 = new Thread(new ThreadStart(ThreadProc1));
thread1.Start();
Thread thread2 = new Thread(new ThreadStart(ThreadProc2));
thread2.Start();
// Console.WriteLine("Main thread: do some work.");
Thread.Sleep(4000);
Console.ReadLine();
}
}
累了,先睡觉。