日期:2014-05-18 浏览次数:20772 次
写了一个例子代码 感觉使用while来扫描不是很好 应该使用同步机制的 using System; using System.Threading; using System.Collections.Generic; namespace ConsoleApplication1 { public class Program { static void Main() { MyThreadPool threadPool = new MyThreadPool(100, 10); threadPool.Start(); Console.ReadKey(); } } /// <summary> /// 自定义线程池 /// </summary> public class MyThreadPool { /// <summary> /// 线程队列 /// </summary> private Queue<Thread> _ThreadQueue; /// <summary> /// 当前线程数 /// </summary> private Int32 _CurThreadCount; /// <summary> /// 同一时间最大能运行的线程数 /// </summary> private Int32 _MaxRunThreadNumber; /// <summary> /// 构造函数 /// </summary> /// <param name="maxThreadNumber">最大线程数</param> /// <param name="maxRunThreadNumber">同一时间最大能运行的线程数</param> public MyThreadPool(Int32 maxThreadNumber,Int32 maxRunThreadNumber) { _ThreadQueue = new Queue<Thread>(maxThreadNumber); if (maxRunThreadNumber > maxThreadNumber) { _MaxRunThreadNumber = maxThreadNumber; } else { _MaxRunThreadNumber = maxRunThreadNumber; } // 初始化线程队列 for (Int32 i = 0; i < maxThreadNumber; i++) { Thread t = new Thread(new ParameterizedThreadStart(Foo)); t.IsBackground = true; t.Name = String.Format("线程{0}", i + 1); _ThreadQueue.Enqueue(t); } _CurThreadCount = 0; } /// <summary> /// 模拟运行工作 /// </summary> /// <param name="threadName"></param> private void Foo(Object threadName) { Random r = new Random(Guid.NewGuid().GetHashCode()); Int32 iSleep = r.Next(1, 10) * 1000; Interlocked.Increment(ref _CurThreadCount); Console.WriteLine(String.Format("{0} 启动,延时 {1} 毫秒, 当前运行线程数据 {2}", threadName, iSleep, _CurThreadCount)); Thread.Sleep(iSleep); Interlocked.Decrement(ref _CurThreadCount); Console.WriteLine(String.Format("{0} 结束", threadName)); } /// <summary> /// 开启线程 /// </summary> public void Start() { while (true) { // 如果线程队列为空,则退出 if (_ThreadQueue.Count == 0) { break; } // 如果当前运行的线程数据小于最大运行数据,就从队列里取一个线程运行 if (_CurThreadCount < _MaxRunThreadNumber) { Thread t = _ThreadQueue.Dequeue(); t.Start(t.Name); } Thread.Sleep(50); } } } }