class Program
{
static void Main(string[] args)
{
//控制台默认输出行数是300,可以设置
Console.BufferHeight = 1000;
TicketSeller t1 = new TicketSeller("A");
TicketSeller t2 = new TicketSeller("B");
Console.ReadLine();
}
}
public class TicketSeller
{
public static int count = 500;
public static object locker = new object();
public TicketSeller(string name)
{
Console.WriteLine(count);
Thread th = new Thread(Sell);
th.Name = name;
th.IsBackground = true;
th.Start();
Console.WriteLine(count);
}
public void Sell()
{
while (count > 0)
{
//引用类型对象在内存中分配的对象头空间(栈空间)最后2bit存放锁标识;lock只要是静态变量就可以,this.GetType()
lock (locker)
{
TicketSeller.count--;
Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "剩余{0}", count);
}
}
}
}
或者使用Monitor
bool isGetLocker = false;
try
{
//引用类型对象在内存中分配的对象头空间(栈空间)最后2bit存放锁标识
Monitor.Enter(locker, ref isGetLocker);
TicketSeller.count--;
Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "剩余{0}", count);
}
catch (Exception e)
{
throw e;
}
finally
{
if (isGetLocker)
{
Monitor.Exit(locker);
}
}
或者给方法标记特性
[MethodImpl(MethodImplOptions.Synchronized)]
线程安全单例模式
class SingleTest
{
private static SingleTest s = null;
private SingleTest() { }
static SingleTest GetSingle()
{
//this,type
lock (typeof(SingleTest))
{
if (s == null)
{ s = new SingleTest(); }
}
return s;
}
}