zoukankan      html  css  js  c++  java
  • 多线程 ThreadPool线程池

    简单说明一下:

    线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程;

    线程池的作用:
    1、线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。
    2、如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止。

    一些使用例子:

    实例一:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace ThreadPoolDemo
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TestThreadPool),new string[] {"drsw","sfs","sdfs"});
    13             Console.ReadKey();
    14         }
    15 
    16         public static void TestThreadPool(object state)
    17         {
    18             string[] arry = state as string[];  //传过来的参数值
    19             int workerThreads = 0;
    20             int completionPortThreads = 0;
    21             System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
    22 
    23             Console.Write(DateTime.Now.ToString() + "--" + arry[0] + "----workerThreads=" + workerThreads + "----completionPortThreads=" + completionPortThreads);
    24         }
    25     }
    26 }

    上述代码运行结果:

    使用例子二:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace ThreadPoolDemo
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TestThreadPool));
    13             Console.ReadKey();
    14         }
    15 
    16         public static void TestThreadPool(object state)
    17         {
    18             int workerThreads = 0;
    19             int completionPortThreads = 0;
    20             System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
    21 
    22             Console.Write(DateTime.Now.ToString() + "----workerThreads=" + workerThreads + "----completionPortThreads=" + completionPortThreads);
    23         }
    24     }
    25 }

    上述代码运行结果:

  • 相关阅读:
    nginx:font-awesome图标刷新后显示不了
    nginx:用openssl生成证书
    安全:http host头攻击漏洞
    js:获得屏幕的宽高
    java中URLEncode与Delphi中关系
    Error during WebSocket handshake: Unexpected response code: 404
    byte数组与MultipartFile相互转化
    Java字符串或数组去掉前后的中括号标签
    IDEA运行新项目时报 Error running ‘XXApplication‘: Command line is too long. Shorten command line for…… 错误
    (转)ElasticSearch中"distinct","count"和"group by"的实现
  • 原文地址:https://www.cnblogs.com/linJie1930906722/p/5661690.html
Copyright © 2011-2022 走看看