线程池

来源:互联网 发布:mysql ibtmp1 编辑:程序博客网 时间:2024/05/03 16:43
    线程池也是一种多线程的处理方式,用于在后台执行多个任务的线程集合,它在处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。每个线程都使用默认的堆栈大小,以默认的优先级运行。
    线程的数目不会超过最大数目。
    

    例 利用线程池创建进程,完成1~40间所有偶数输出。

using System;using System.Collections.Generic;using System.Threading;using System.Linq;using System.Text;namespace threadJoing2{            class Program    {        public void Method(object state)        {            string name = DateTime.Now.Millisecond.ToString();            if (state == null)            {                Console.WriteLine("无参数方法{0}开始执行:", name);            }            else            {                Console.WriteLine("{0}线程开始执行",state.ToString());            }            int n = 0;            lock (this)            {                for (int i = 1; i <= 40; i++)                {                    if (i % 2 == 0)                    {                        n++;                        Console.Write(i+"\t");                        if (n % 8 == 0)                        {                            Console.WriteLine();                            Thread.Sleep(500);                        }                    }                }            }            if (state == null)                Console.WriteLine("\n{0}无参方法结束", name);            else                Console.WriteLine("\n{0}线程结束执行",state);        }        static void Main(string[] args)        {            Program th = new Program();            ThreadPool.QueueUserWorkItem(new WaitCallback(th.Method));            Thread.Sleep(100);            ThreadPool.QueueUserWorkItem(new WaitCallback(th.Method),"采用带参数的方法");            Console.ReadLine();        }    }}




0 0