这是一个多线程同时读取一个数组的示例,是回答了一个网友提问的文章.
- private static string[] Arr = new string[1000];
- private static int arrindex = 0;
- const int N = 5;
- private static ManualResetEvent ent = new ManualResetEvent(false);
- static void Main()
- {
- for (int i = 0; i < 1000; i++)
- {
- Arr[i] = i.ToString();
- }
- arrindex = 0;
- for (int threadnum = 0; threadnum < N; threadnum++)
- {
- Thread s = new Thread(OutputN);
- s.Name = "thread" + threadnum.ToString();
- s.IsBackground = true;
- s.Start();
- Thread.Sleep(0);
- }
- Console.Read();
- }
- private static void OutputN()
- {
- while (arrindex < 1000)
- {
- lock (Arr)
- {
- Console.WriteLine("Thread{0} Arr{1} is: {2}", Thread.CurrentThread.Name, arrindex, Arr[arrindex]);
- arrindex++;
- }
- Thread.Sleep(0);
- }
- }
小结
运行下就可以看出结果来了,例子不会很难,但是可能存在数组越界的问题,我自己测试是测试不出来,但是,有人复制了就会出现越界问题.如果你测试了发现了问题,请不要吝啬告诉我,谢谢.