线程池

线程池中的线程:

  1、本身都是后台线程

  2、线程可以进行重用

线程池内部原理图

10000个线程池 VS 500个线程 执行时间

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Threading;
 7 using System.Diagnostics;
 8 
 9 namespace 线程池练习
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Stopwatch sw = new Stopwatch();
16             sw.Start();
17             for (int i = 0; i < 500; i++)
18             {
19                 new Thread(()=> {
20                     int j = 0;
21                     j++;
22                 }).Start();
23             }
24             sw.Stop();
25             Console.WriteLine("执行时间:"+sw.Elapsed.TotalSeconds);
26             Console.ReadKey();
27         }
28     }
29 }
线程

执行时间

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Threading;
 7 using System.Diagnostics;
 8 
 9 namespace 线程池练习
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Stopwatch sw = new Stopwatch();
16             sw.Start();
17             for (int i = 0; i < 10000; i++)
18             {
19                 ThreadPool.QueueUserWorkItem((s) =>
20                 {
21                     int j = 0;
22                     j++;
23                 });
24             }
25             Console.WriteLine("执行时间:" + sw.Elapsed.TotalSeconds);
26             Console.ReadKey();
27         }
28     }
29 }
线程池

 

 什么时候用线程池?什么时候用手动创建线程?

1、能用线程池的就用线程池,处理顺序不确定

2、我们想手动关闭线程的话,那么必须手动创建了。Abort()   Join()

3、我们需要对线程池的线程的优先级做设置的情景下,只能使用手动创建线程。

4、如果执行的线程执行时间特别长。线程池:适合做大量小运算

获取线程池最大的线程数据

1         static void Main(string[] args)
2         {
3             int numMax = 0;
4             int runNumMax = 0;
5             ThreadPool.GetMaxThreads(out numMax, out runNumMax);
6             Console.WriteLine("线程池中辅助线程的最大数目:"+numMax+ ",线程池中异步 I/O 线程的最大数目:"+runNumMax);
7             Console.ReadKey();
8         }

 

posted @ 2019-06-17 23:36  陈彦斌  阅读(263)  评论(0编辑  收藏  举报