博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

线程池的使用

Posted on 2008-06-16 13:45  懒人ABC  阅读(912)  评论(1编辑  收藏  举报
目的:
      能动地有效地处理繁忙的客户段请求。
做法:
      开启多个线程,使用分流形式处理客户段的请求。
      包括创建自己的线程池和使用系统提供的线程池。

例子:创建自己的线程池
       
using System.Threading;

class MyThreadPool
{
      ReusableThread[] m_ThreadPool;

      public MyThreadPool(int pSize)
      {
           m_ThreadPool = new ReusableThread[pSize];
           
           for(int i=0; i<pSize; i++)
           {
                m_ThreadPool[i] = new ReusableThread();
           }
      }

      public ReusableThread GetThread()
      {
           lock(this)
           {
               ReusableThread vThread = GetAvailableThread();
               
               return vThread;
           }
      }

      public ReusableThread GetAvailableThread()
      {
          ReusableThread vReturnThread = null;

          foreach(ReusableThread vThread in m_ThreadPool)
          {
                 if(vThread.IsAvailable)
                 {
                      vThread.IsAvailable = false;
                      vReturnThread = vThread;
                      
                      break;
                 }
          }

          return vReturnThread;
      }

      public void PutThread(ReusableThread pThread)
      {
          lock(this)
          {
                pThread.IsAvailable = true;
          }
      }
}
//--------------------------------ReusableThread-------------------
       public delegate void StartupMethod();
       class ReusableThread
       {
           private Thread m_Thread;
           public bool IsAvailable = true;
           private StartupMethod m_StartupMethod;

           public ReusableThread()
           {
                m_Thread = new Thread(new ThreadStart(CommonStart));
           }

           public void Join()
           {
               m_Thread.Join();
           }

           public void Run(StartupMethod pStartupMethod)
           {
               m_StartupMethod = pStartupMethod;
               m_Thread.Start();
           }

           public void CommonStart()
           {
                if(m_StartupMethod != null)
              {
                    m_StartupMethod();
                    m_StartupMethod 
= null;
               }

           }
      }

//---------------------------Excute code----------------
public class mainApp
{
     public void RunWithThread()
     {
          MyThreadPool vPool = new MyThreadPool(20);
          ReusableThread vThead = vPool.GetThread();
          if(vThread == null)
          {
                return;
          }
          else
          {
               vThread.Run(new StartupMethod(MyCode));
               vThread.Join();
               vPool.PutThread(vThread);
          }
     }
    
      public void MyCode()
      {
           Thread.Sleep(2000);
      }
}