首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

怎样让多条线程顺序执行?该如何处理

2012-04-23 
怎样让多条线程顺序执行???for (int i 0 i 10 i++){new Thread(delegate(){//MyCode}).Start()}//

怎样让多条线程顺序执行???
for (int i = 0; i < 10; i++)
  {
  new Thread(
  delegate()
  {
  //MyCode;
  }
  ).Start();

  }
//怎么让循环中的线程按照I的顺序先后执行,是用Lock锁吗?
//应该怎么锁,请大侠指点

[解决办法]

C# code
static void Main(string[] args){    int order = 0;//, -1 for exit , 0 for initialize    int ordermax = 0;//最大编号    ParameterizedThreadStart threadProc = p =>        {            if (!(p is int)) return;            int myOrder = (int)p;            object sync = new object();            while (true)            {                lock (sync)//同步线程                {                    if (order != myOrder)//判断状态机当前状态是否是到自己执行                    {                        Thread.Sleep(50);//阻塞自己线程50毫秒后继续下一次检测                        continue;                    }                    Console.WriteLine(p);//实际操作                    order++;//在lock块中,安全的操作状态                    if (order > ordermax) order = 1;//循环状态                }                Thread.Sleep(50);            }        };    new Thread(threadProc).Start(1);//启动1个线程,编号1    new Thread(threadProc).Start(2);//启动1个线程,编号2    new Thread(threadProc).Start(3);//启动1个线程,编号3    new Thread(threadProc).Start(4);//启动1个线程,编号4    ordermax = 4;//最大值4    order = 1;//当前状态1,开始启动    Console.ReadKey();}
[解决办法]
thread.Join(); 不就可以了么
C# code
        public const int Repetitions = 10000;        public static void Main()        {            //Thread thread = new Thread(DoWork);            //thread.Start(".");            //thread.Join();            //for (int count = 0; count < Repetitions; count++)            //{            //    Console.Write('-');            //}            Thread thread;            for (int i = 0; i < 3; i++)            {                thread = new Thread(DoWork);                if (i == 0)                {                    thread.Start(".");                }                else if (i == 1)                {                    thread.Start("-");                }                else if (i == 2)                {                    thread.Start("*");                }                else {                    thread.Start("&");                }                thread.Join();            }                        Console.ReadLine();        }        public static void DoWork(object state)        {            for (int count = 0; count < Repetitions; count++)            {                Console.Write(state);            }        }    } 

热点排行