zoukankan      html  css  js  c++  java
  • 普通线程和线程池运行时间对比

      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();
                    
                }
            }
  • 相关阅读:
    HNOI2019 JOJO
    十二省联考2019 骗分过样例
    十二省联考2019 皮配
    十二省联考2019 字符串问题
    十二省联考2019 春节十二响
    十二省联考2019 异或粽子
    HNOI2019 白兔之舞 dance
    HNOI2019 多边形 polygon
    HNOI2019 鱼 fish
    P4770 [NOI2018]你的名字
  • 原文地址:https://www.cnblogs.com/sportdog/p/9528231.html
Copyright © 2011-2022 走看看