多线程信号源的理解

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Threading;
   6:   
   7:  namespace CatVSMice
   8:  {
   9:      class Program
  10:      {
  11:          /// <summary>
  12:          /// 猫队的命令。
  13:          /// </summary>
  14:          static EventWaitHandle catCommand = new AutoResetEvent(false);
  15:   
  16:          static void Main(string[] args)
  17:          {            
  18:              new Thread(CatArmy).Start();//部队准备            
  19:              string str = "";
  20:              while (true)
  21:              {
  22:                  //等待猫军队集结完毕
  23:                  Thread.Sleep(1000);
  24:   
  25:                  Console.WriteLine("猫警长下达命令(ATTACK:攻击/NOATTACK:不攻击):");
  26:                  str = Console.ReadLine();
  27:                  if (str == "ATTACK")
  28:                  {
  29:                      catCommand.Set();//进攻命令
  30:                      break;
  31:                  }
  32:                  else
  33:                  {
  34:                      Console.WriteLine("猫队需要调整作战计划,部队暂按兵不动。");
  35:                  }
  36:                  Thread.Sleep(3000);
  37:              }
  38:   
  39:              Console.ReadLine();
  40:          }
  41:   
  42:          /// <summary>
  43:          /// 猫队部队移动
  44:          /// </summary>
  45:          static void CatArmy()
  46:          {
  47:              Console.WriteLine("猫队准备就绪,请队长下达命令!部队等待中。。。");
  48:              catCommand.WaitOne();//等待命令
  49:              Console.WriteLine("向老鼠发起进攻。。。");
  50:              Thread.Sleep(2000);
  51:              Console.WriteLine("猫队获得胜利!!!!!");
  52:              //Console.WriteLine("鼠军已被击败,是否全歼?!请下达命令:");
  53:   
  54:          }
  55:      }
  56:  }

其实关于理解这块的东西用红绿灯的实例更能说明问题:
static EventWaitHandle lightState = new AutoResetEvent(false);
Main():
如果是红灯:则Thread.Sleep(3000);
lightState.Set();

人过红绿灯的方法
lightState.WaitOne();
Console.WriteLine(“可以过马路了!”);
空了我再写一个例子吧。

posted @ 2013-04-16 12:45  pnljs  阅读(300)  评论(0编辑  收藏  举报