C#多线程赛跑实例
》,这次我们写一个多线程的赛跑实例,内容很简单:超人和易做图侠赛跑,因为超人飞的比易做图侠跳的快,为了公平,我们让易做图侠跑的长度小点,裁判负责宣布比赛的开始和结束。
[csharp]
class MultiThread
{
//定义两个线程,分别为超人和易做图侠
private static Thread SuperMan;
private static Thread SpiderMan;
//程序入口,比赛开始
static void Main(string[] args)
{
//初始化数据
InitData();
//裁判吹哨,开始赛跑
JudgeWork();
}
/// <summary>
/// 初始化超人和易做图侠的线程和姓名
/// </summary>
private static void InitData()
{
SuperMan = new Thread(new ParameterizedThreadStart(RunnerWork));
SpiderMan = new Thread(new ParameterizedThreadStart(RunnerWork));
SuperMan.Name = "SuperMan";
SpiderMan.Name = "SpiderMan";
}
/// <summary>
/// 裁判开始比赛,最后宣布胜者
/// </summary>
private static void JudgeWork()
{
Console.WriteLine("{0} PK {1}", SuperMan.Name, SpiderMan.Name);
Console.WriteLine("比赛即将开始,请各位做好准备!");
Console.WriteLine("预备!");
Console.Read();
//Superman起跑
Console.WriteLine("回车枪响,Superman开始起跑!");
Console.Beep(654, 1200);
SuperMan.Start(500);
//Monster起跑
Console.WriteLine("回车枪响,SpiderMan开始起跑!");
SpiderMan.Start(200);
SuperMan.Join();
SpiderMan.Join();
//宣布赛跑结果
Console.WriteLine("我宣布比赛结束");
//程序暂停12秒
Thread.Sleep(12000);
}
/// <summary>
/// 赛跑的过程
/// </summary>
/// <param name="obj">赛跑参数</param>
private static void RunnerWork(Object obj)
{
int length = Int32.Parse(obj.ToString());
Thread CurrentThread = Thread.CurrentThread;
string CurThreadName = CurrentThread.Name;
int speed;
//超人速度为20
if (CurThreadName == SuperMan.Name)
{
speed = 50;
}
//易做图侠速度为20
else if (CurThreadName == SpiderMan.Name)
{
speed = 20;
}
//如果不可控线程进入,采用以下速度
else
{
speed = 1;
}
Console.WriteLine("{0},开始起跑…………", CurThreadName);
for (int count = speed; count <= length; count += speed)
{
Thread.Sleep(1000);
Console.WriteLine("{0}……跑到了第{1}米", CurThreadName, count.ToString());
}
Console.WriteLine("{0},到达终点!了咧欢迎……", CurThreadName);
}
}
class MultiThread
{
//定义两个线程,分别为超人和易做图侠
private static Thread SuperMan;
private static Thread SpiderMan;
//程序入口,比赛开始
static void Main(string[] args)
{
//初始化数据
InitData();
//裁判吹哨,开始赛跑
JudgeWork();
}
/// <summary>
/// 初始化超人和易做图侠的线程和姓名
/// </summary>
private static void InitData()
{