首先先说一个线程不同步的例子吧,以下为售票员的模拟售票,多个售票员出售100张门票,代码如下:
using System;
using System.Text;
using System.Collections.Generic;
using System.Threading;
namespace threadTest
{
class Program
{
class ThreadLock
{
private Thread thread_1;
private Thread thread_2;
private List<int> tickets;
private object objLock = new object();//对象锁的对象
public ThreadLock()
{
thread_1 = new Thread(Run);
thread_1.Name = "Sailer_1";
thread_2 = new Thread(Run);
thread_2.Name = "Sailer_2";
}
public void Start()
{
tickets = new List<int>(100);
for(int i = 1; i <= 100; i++)
{
tickets.Add(i);
}
thread_1.Start();
thread_2.Start();
}
public void Run()
{
while (tickets.Count > 0)
{
int get = tickets[0];
Console.WriteLine("{0} sail a ticket ,ticket number :{1} ",
Thread.CurrentThread.Name, get.ToString());
tickets.RemoveAt(0);
Thread.Sleep(1);
}
}
}
static void Main()
{
ThreadLock TK = new ThreadLock();
TK.Start();
Console.ReadKey();
}
}
}
以上为一个模拟售票系统,两个线程对一个票箱进行操作,每次都取出最上层的票,然后输出,运行之后查看结果会发现在在同一张票上,两个线程都可能同时卖出,如下: