C# 如何让 多线程中每个线程间隔毫秒执行同一个方法

原文:http://bbs.csdn.net/topics/391020219#post-399131587

class Program
    {
        static int dur = 200;
        static string tm = "";
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                var td = new Thread(new ThreadStart(
                () =>
                {
                    lock (tm)
                    {
                        if (tm == "")
                        {
                            Thread.Sleep(dur);
                        }
                        else
                        {
                            var t=DateTime.Now.Subtract(DateTime.Parse(tm));
                            Thread.Sleep(dur - (int)t.TotalSeconds);
                        }
                    };
                    DoSomeThing();
                }
                    ));
                td.Start();
            }
            Console.Read();
        }
 
        private static void DoSomeThing()
        {
            tm = DateTime.Now.ToShortTimeString();
            string info = string.Format("线程ID:{0},执行时间:{1}"
              , Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:ffff"));
            Console.WriteLine(info);
            Thread.Sleep(5000);
        }
    }


你可能感兴趣的:(thread,Lock)