代码改变世界

线程池 的实现

2011-09-22 14:04  yuejianjun  阅读(161)  评论(0编辑  收藏  举报
  先 一个线程
算出
baseNumber值,其它线程再向下执行,当所有线程执行完后,返回结果

  class Calculate
    {
        //基数、数1、数2、数3
        double baseNumber, firstTerm, secondTerm, thirdTerm;
        //自动重置同步事件数组
        AutoResetEvent[] autoEvents;
        //手动重置同步事件
        ManualResetEvent manualEvent;
        //随机数生成器
        Random randomGenerator;

        public Calculate()
        {
            //初始化同步事件
            autoEvents = new AutoResetEvent[]
                     {
                         new AutoResetEvent(false),
                         new AutoResetEvent(false),
                         new AutoResetEvent(false)
                     };

            manualEvent = new ManualResetEvent(false);
        }

        void CalculateBase(object stateInfo)
        {
            baseNumber = randomGenerator.NextDouble();

            //置事件状态为终止状态,使等待线程继续
            manualEvent.Set();//其它线程才可以向下执行
        }

        void CalculateFirstTerm(object stateInfo)
        {
            double preCalc = randomGenerator.NextDouble();
            //等待手动重置事件终止
            manualEvent.WaitOne();
            firstTerm = preCalc * baseNumber * randomGenerator.NextDouble();
            //置自动事件终止信号
            autoEvents[0].Set();
        }

        void CalculateSecondTerm(object stateInfo)
        {
            double preCalc = randomGenerator.NextDouble();
            //等待手动重置事件终止
            manualEvent.WaitOne();
            secondTerm = preCalc * baseNumber * randomGenerator.NextDouble();
            //置自动事件终止信号
            autoEvents[1].Set();
        }

        void CalculateThirdTerm(object stateInfo)
        {
            double preCalc = randomGenerator.NextDouble();
            //等待手动重置事件终止
            manualEvent.WaitOne();
            thirdTerm = preCalc * baseNumber * randomGenerator.NextDouble();
            //置自动事件终止信号
            autoEvents[2].Set();
        }

        public double Result(int seed)
        {
            randomGenerator = new Random(seed);

            //将待执行工作加入线程
            ThreadPool.QueueUserWorkItem(new WaitCallback(CalculateBase));
            ThreadPool.QueueUserWorkItem(new WaitCallback(CalculateFirstTerm));
            ThreadPool.QueueUserWorkItem(new WaitCallback(CalculateSecondTerm));
            ThreadPool.QueueUserWorkItem(new WaitCallback(CalculateThirdTerm));

            //等待所有自动事件终止
            WaitHandle.WaitAll(autoEvents);
            //重置手动事件为非终止状态
            
//manualEvent.Reset();

            return firstTerm + secondTerm + thirdTerm;
        }

    }

 

调用:         

  Calculate calc = new Calculate();

  Console.WriteLine("Result = {0}.", calc.Result(234).ToString());