码迷,mamicode.com
首页 > 编程语言 > 详细

多线程19-线程池批量插入线程

时间:2016-06-23 12:46:55      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:

    class Program
    {
        static void UseThreads(int numberOfOperations)
        {
            using (var countdown = new CountdownEvent(numberOfOperations))
            {
                Console.WriteLine("Scheduling work by creating threads");
                for (int i = 0; i < numberOfOperations; i++)
                {
                    var thread = new Thread(() =>
                    {
                        Console.WriteLine("current Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                        countdown.Signal();
                    });
                    thread.Start();
                }
                countdown.Wait();
                Console.WriteLine();
            }
        }
        static void UseThreadPool(int numberOfOperations)
        {
            using (var countdown = new CountdownEvent(numberOfOperations))
            {
                Console.WriteLine("Starting work on a threadPool");
                for (int i = 0; i < numberOfOperations; i++)
                {
                    ThreadPool.QueueUserWorkItem(x =>
                     {
                         Console.WriteLine("current Thread Id={0}", Thread.CurrentThread.ManagedThreadId);
                         Thread.Sleep(TimeSpan.FromSeconds(0.1));
                         countdown.Signal();
                     });
                }
                countdown.Wait();
                Console.WriteLine();
            }
        }
        static void Main()
        {
            const int numberOfOpeartions = 3000;
            var sw = new Stopwatch();
            sw.Start();
            UseThreads(numberOfOpeartions);
            sw.Stop();
            Console.WriteLine("Excution time using threads:{0}", sw.ElapsedMilliseconds);

            sw.Reset();
            sw.Start();
            UseThreadPool(numberOfOpeartions);
            sw.Stop();
            Console.WriteLine("Execution time using threads:{0}", sw.ElapsedMilliseconds);
        }
    }

多线程19-线程池批量插入线程

标签:

原文地址:http://www.cnblogs.com/shidengyun/p/5610126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!