您的位置:首页 > 其它

多线程生成海量数据和多线程海量数据查找

2016-07-24 21:36 316 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.Diagnostics;

namespace MultiThreadMaxNumber

{

    class Program

    {

        static Random random = new Random();

        const int length = 100000000;  /*数据总量*/

        static int[] data = new int[length];  /*数据集合*/

        static int finishNum = 0;

        static AutoResetEvent locker = new AutoResetEvent(false);

        static int maxNumber = int.MinValue;  /*获取最大数据*/

        static void Main(string[] args)

        {

            Console.WriteLine("海量数据生成开始,随机生成{0}个数据", length);

            for (int i = 0; i < 10; i++)

            {

                Thread thread = new Thread(new ParameterizedThreadStart(getRamdonData));

                thread.Start(i);

            }

            locker.WaitOne(); /*等待所有线程结束*/

            finishNum = 0;

            locker.Reset();  /*重新唤起线程*/

            Console.WriteLine("在{0}个数据中寻找最大数据开始",length);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            for (int i = 0; i < 10; i++)

            {

                Thread thread = new Thread(new ParameterizedThreadStart(getMaxValue));

                thread.Start(i);

            }

            locker.WaitOne(); /*等待所有线程结束*/

            Console.WriteLine("最大数据为{0}", maxNumber);

            sw.Stop();

            TimeSpan ts2 = sw.Elapsed;

            Console.WriteLine("线程结束耗时{0}s.", ts2.TotalMilliseconds/1000);

            sw.Start();

            Array.Sort(data); /*耗时相当厉害*/

            Console.WriteLine("srot maxData={0}", data[99999999]);

            sw.Stop();

            ts2 = sw.Elapsed;

            Console.WriteLine("排序计算结束耗时{0}s.", ts2.TotalMilliseconds/1000);

        }

        static void getRamdonData(object region)

        {

            int begin = (int)region * length / 10;

            int end = ((int)region + 1) * length / 10;

            Console.WriteLine("开始生成{0}到{1}之间的数据",begin, end);

            for (int i = begin; i < end; i++)

            {

                data[i] = random.Next(int.MinValue, int.MaxValue); /*随机生成数据*/

            }

            Console.WriteLine("{0}到{1}之间的数据生成完毕", begin, end);

            finishNum++;

            if (finishNum == 10) locker.Set(); /*释放线程锁*/

        }

        static void getMaxValue(object region)

        {

            int begin = (int)region * length / 10;

            int end = ((int)region + 1) * length / 10;

            for (int i = begin; i < end; i++)   /*这一段可以优化*/

                maxNumber = Math.Max(maxNumber, data[i]);

            finishNum++;

            if (finishNum == 10) locker.Set(); /*释放线程锁*/

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: