标签:RKE led 对象 线程池 10个 get 最大 管线 item
线程的创建需要时间。如果存在多个任务需要完成,则可以事先创建许多线程,在应该完成任务时发出需求线程请求。线程数最好时动态的增加于减少。TheadPool类可以托管线程列表,这个类能动态增加于减少线程的线程数,直到最大线程数----可配置。在四核CPU中,默认为1023个工作线程和1000个I/O线程。也可以指定创建线程池时应该立即启动的最小线程数,以及可用最大线程数。如果有新的任务,但是线程池中已没有闲于线程,那么新任务需要排队,等待线程完成其任务。如下示例:
static void Main() { int nWorkerThreads; int nCompletionPortThreads; ThreadPool.GetMaxThreads(out nWorkerThreads, out nCompletionPortThreads); Console.WriteLine("Max worker threads: {0}, I/O completion threads: {1}", nWorkerThreads, nCompletionPortThreads for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(JobForAThread); //WaitCallback类型委托:线程池线程要执行的回调方法 } Thread.Sleep(3000); /*******************输出结果***************************** * Max worker threads: 1023, I/O completion threads: 1000 * loop 0, running inside pooled thread 3 * loop 0, running inside pooled thread 4 * loop 0, running inside pooled thread 7 * loop 0, running inside pooled thread 6 * loop 0, running inside pooled thread 8 * loop 0, running inside pooled thread 9 * loop 0, running inside pooled thread 10 * loop 0, running inside pooled thread 5 * loop 1, running inside pooled thread 6 * loop 1, running inside pooled thread 4 * loop 1, running inside pooled thread 7 * loop 1, running inside pooled thread 3 * loop 1, running inside pooled thread 5 * loop 1, running inside pooled thread 8 * loop 1, running inside pooled thread 10 * loop 1, running inside pooled thread 9 * loop 2, running inside pooled thread 6 * loop 2, running inside pooled thread 4 * loop 2, running inside pooled thread 5 * loop 2, running inside pooled thread 7 * loop 2, running inside pooled thread 3 * loop 2, running inside pooled thread 8 * loop 2, running inside pooled thread 10 * loop 2, running inside pooled thread 9 * loop 0, running inside pooled thread 6 * loop 0, running inside pooled thread 4 * loop 1, running inside pooled thread 6 * loop 1, running inside pooled thread 4 * loop 2, running inside pooled thread 6 * loop 2, running inside pooled thread 4 * *******************************************************/ } static void JobForAThread(object state) { for (int i = 0; i < 3; i++) { Console.WriteLine("loop {0}, running inside pooled thread {1}", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(50); } }
10个任务,只由8个线程池中的线程处理(因为CPU是8核)。线程池虽然简单,但是有如下限制:
标签:RKE led 对象 线程池 10个 get 最大 管线 item
原文地址:https://www.cnblogs.com/pilgrim/p/9245467.html