当前位置:编程学习 > C#/ASP.NET >>

多线程例子

下面是开启了两个线程,就以这两个线程为例,进行测试吧

 static void Main(string[] args)
        {
            ThreadStart sptintnumb = new ThreadStart(PrintNumb);
            Thread tnumb = new Thread(sptintnumb);
            ThreadStart sprintstr = new ThreadStart(PrintStr);
            Thread trintstr = new Thread(sprintstr);

            Stopwatch watch = new Stopwatch();
            watch.Start();
            trintstr.Start();
            tnumb.Start();
            //起一个循环,不断判断线程的执行状态
            while (true)
            {
                if(trintstr.ThreadState==System.Threading.ThreadState.Stopped && tnumb.ThreadState==System.Threading.ThreadState.Stopped)
                {
                    watch.Stop();
                    Console.WriteLine(watch.Elapsed.TotalMilliseconds);
                    break;
                }
            }
            Console.ReadKey();
        }
        private static void PrintNumb()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(i);
            }
        }
        private static void PrintStr()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine("你输入的是:"+i.ToString());
            }
        }

 

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,