C#Fibonacci多线程测试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace _100tempTest
{
    /// <summary>
    /// 黄金分割数列:1,1,2,3,5,8,13,21...
    /// </summary>
    class Fibonacci_斐波那契线程池测试
    {
        /// <summary>
        /// 输入测试
        /// </summary>
        private int _n;
        private ManualResetEvent _doneEvent;
        /// <summary>
        /// 计算结果
        /// </summary>
        private int _fiboFN;
        /// <summary>
        /// 开始时间
        /// </summary>
        private DateTime _startTime;
        /// <summary>
        /// 结束时间
        /// </summary>
        private DateTime _endTime;
        public int N { get { return _n; } }
        public int FiboFN { get { return _fiboFN; } }
        public DateTime StartTime { get { return _startTime; } }
        public DateTime EndTime { get { return _endTime; } }

        public Fibonacci_斐波那契线程池测试(int n,ManualResetEvent doneEvent)
        {
            this._n = n;
            this._doneEvent = doneEvent;
        }

        public int Recursion_递归(int n)
        {
            if (n < 3)
            {
                return 1;
            }
            else
            {
                return Recursion_递归(n-1)+ Recursion_递归(n - 2);
            }
        }

        public void ThreadPoolCallback(object threadContext)
        {
            int threadIndex = (int)threadContext;
            //开始
            _startTime = DateTime.Now;
            _fiboFN = Recursion_递归(_n);
            //结束
            _endTime = DateTime.Now;
            _doneEvent.Set();
        }
    }

    public class TestClass
    {
        public void Test()
        {
            const int FibonacciCalculations = 5;//定义5个斐波那契数
            ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
            Fibonacci_斐波那契线程池测试[] fibonacciArray = new Fibonacci_斐波那契线程池测试[FibonacciCalculations];
            Random random = new Random();
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                Fibonacci_斐波那契线程池测试 fibonacci_ = new Fibonacci_斐波那契线程池测试(random.Next(30,42), doneEvents[i]);
                fibonacciArray[i] = fibonacci_;
                ThreadPool.QueueUserWorkItem(fibonacci_.ThreadPoolCallback,i);
            }
            //等待全部结束方法一:
            //WaitHandle.WaitAll(doneEvents);//报错不支持一个 STA 线程上针对多个句柄的 WaitAll,是因为默认main函数上的[STAThread]为单线程程序,注释即可。
                                           
            foreach (var item in doneEvents)//等待全部结束方法二
            {
                item.WaitOne();
            }
            List<int> fbArray = new List<int>();
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                fbArray.Add(fibonacciArray[i].FiboFN);
            }
        }

    }
}

  

posted @ 2022-03-13 22:25  SHW03  阅读(42)  评论(0编辑  收藏  举报