C#多线程编程(2):线程的同步
2010-09-30 21:09:36 来源:WEB开发网线程不同步引出的问题
下面做一个假设,假设有100张票,由两个线程来实现一个售票程序,每次线程运行时首先检查是否还有票未售出,如果有就按照票号从小到大的顺序售出票号最小的票,程序的代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace StartThread
{
public class ThreadLock
{
private Thread threadOne;
private Thread threadTwo;
private List<string> ticketList;
private object objLock = new object();
public ThreadLock()
{
threadOne = new Thread(new ThreadStart(Run));
threadOne.Name = "Thread_1";
threadTwo = new Thread(new ThreadStart(Run));
threadTwo.Name = "Thread_2";
}
public void Start()
{
ticketList = new List<string>(100);
for (int i = 1; i <= 100; i++)
{
ticketList.Add(i.ToString().PadLeft(3,'0'));//实现3位的票号,如果不足3位数,则以0补足3位
}
threadOne.Start();
threadTwo.Start();
}
private void Run()
{
while (ticketList.Count > 0)//①
{
string ticketNo = ticketList[0];//②
Console.WriteLine("{0}:售出一张票,票号:{1}", Thread.CurrentThread.Name, ticketNo);
ticketList.RemoveAt(0);//③
Thread.Sleep(1);
}
}
}
}