zoukankan      html  css  js  c++  java
  • 并发:线程池异步执行与创建单独的线程执行

    线程池与并行度

    了解线程池如何工作于大量的异步操作,以及它与创建大量单独的线程的方式的不同之处。

    实例代码验证

            static void Main(string[] args)
            {
                const int numberOfOperations = 500;
                var sw = new Stopwatch();
                sw.Start();
                UseThreads(numberOfOperations);
                sw.Stop();
                Console.WriteLine("Thread Execution time using threads: {0}", sw.ElapsedMilliseconds);
    
                sw.Reset();
                sw.Start();
                UseThreadPool(numberOfOperations);
                sw.Stop();
                Console.WriteLine("ThreadPool Execution time using threads: {0}", sw.ElapsedMilliseconds);
    
                Console.ReadKey();
            }
    
            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.Write("{0},", Thread.CurrentThread.ManagedThreadId);
                            Thread.Sleep(TimeSpan.FromSeconds(0.1));
                            countdown.Signal();//注册当前线程
                        });
                        //thread.IsBackground = true;
                        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( _ => {
                            Console.Write("{0},", Thread.CurrentThread.ManagedThreadId);
                            Thread.Sleep(TimeSpan.FromSeconds(0.1));
                            countdown.Signal();//注册当前线程
                        });
                    }
                    countdown.Wait();
                    Console.WriteLine();
                }
            }

    Thread Execution time using threads: 5211
    ThreadPool Execution time using threads: 5948

    结论

    线程池为操作系统节省了内存和线程数,但是也为此付出了更长的执行时间。

  • 相关阅读:
    emacs窗口切换神器--window-numbering
    yum命令总结
    Emacs快捷键设置
    emacs常用命令
    Emacs编辑远程服务器中的文件
    (转)emacs安装cedet和ecb
    (转)replace 和 on duplicate key update语句
    HashMap解决hash冲突的方法
    程序员的学习和积累
    HttpClient 设置代理方式
  • 原文地址:https://www.cnblogs.com/lztkdr/p/8378224.html
Copyright © 2011-2022 走看看