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

     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);
        }
    }

转载于:https://www.cnblogs.com/shidengyun/p/5610126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值