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

    结论

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

  • 相关阅读:
    解决Android Studio Gradle DSL method not found: 'android()'
    【转】关于ListView中notifyDataSetChanged()刷新数据不更新原因
    设计模式-单例模式
    IE浏览器让DIV居中
    Java通过DOM解析XML
    git 配置文件位置;git配置文件设置
    git config配置
    dos2unix
    文件的编码问题解决
    git diff old mode 100644 new mode 100755
  • 原文地址:https://www.cnblogs.com/lztkdr/p/8378224.html
Copyright © 2011-2022 走看看