sportdog

导航

 

 

  const int intNumber = 500;
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            UseThreads(intNumber);
            sw.Stop();
            Console.WriteLine("用线程执行时间:{0}", sw.ElapsedMilliseconds);
            sw.Reset();
            sw.Start();
            UseThreadPool(intNumber);
            sw.Stop();
            Console.WriteLine("用线程执行时间:{0}", sw.ElapsedMilliseconds);

        }


        private static void UseThreadPool(int numberOfOperation)
        {
            using (var countdown = new CountdownEvent(numberOfOperation))
            {
                Console.WriteLine("开始创建线程:线程池");
                for (int i = 0; i < numberOfOperation; i++)
                { 
                    ThreadPool.QueueUserWorkItem(p=>{
                        Console.WriteLine("{0}", Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                        countdown.Signal();
                    });
                }
                countdown.Wait();
                Console.WriteLine();
            }
        }

        private static void UseThreads(int numberOfOperation)
        { 
            using(var countdown = new CountdownEvent(numberOfOperation))
            {
                Console.WriteLine("开始创建线程:线程");
                for (int i = 0; i < numberOfOperation; i++)
                {
                    Thread thread = new Thread(() =>
                    {
                        Console.WriteLine("{0}", Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                        countdown.Signal();

                    });
                    thread.Start();
                }
                countdown.Wait();
                Console.WriteLine();
                
            }
        }

 

posted on 2018-08-24 10:21  sportdog  阅读(437)  评论(1编辑  收藏  举报