例子1:
namespace GCApp
{
class Program
{
private static readonly object o = new object();
static void Main(string[] args)
{
TicketSeller t = new TicketSeller("张三");
TicketSeller t1 = new TicketSeller("李四");
Console.ReadKey();
}
}
public class TicketSeller
{
static int signal = 0;
static int count = 100;
public TicketSeller(string name)
{
Thread t = new Thread(Sell);
t.Name = name;
t.IsBackground = true;
t.Start();
}
public void Sell()
{
while (count > 0)
{
if (0 == Interlocked.Exchange(ref signal, 1))//加锁
{
TicketSeller.count--;
//Interlocked.Decrement(ref count);也可以用总方式来进行自减
Console.WriteLine("{0}卖出一张票,还有{1}张", Thread.CurrentThread.Name, count);
Interlocked.Exchange(ref signal, 0); //解锁
}
}
}
}
}
列子2:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static int count = 100; //这个int必须是静态的
static int signal = 0; //这个int必须是静态的
static void Main(string[] args)
{
for (int i = 0; i < 50; i++)
{
//通过Interlocked实现自旋锁。
Task.Run(new Action(new Program().Subtraction));
Task.Run(new Action(new Program().Subtraction));
}
Console.ReadKey();
}
public void Subtraction()
{
while (Interlocked.Exchange(ref signal, 1) != 0) { }//加自旋锁
Program.count--; //业务操作
Console.WriteLine(count);
Interlocked.Exchange(ref signal, 0); //释放锁
}
}
}