用C#遍历一千万个数字,利用十个线程同时显示结果
时间: 2024-01-21 09:19:11 浏览: 20
以下是一个基本的示例代码,可以用于遍历一千万个数字并利用十个线程同时显示结果:
```csharp
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10000000];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = i + 1;
}
int numThreads = 10;
int chunkSize = arr.Length / numThreads;
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
{
int startIndex = i * chunkSize;
int endIndex = (i == numThreads - 1) ? arr.Length : (i + 1) * chunkSize;
threads[i] = new Thread(() =>
{
for (int j = startIndex; j < endIndex; j++)
{
Console.WriteLine(arr[j]);
}
});
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
Console.WriteLine("Done");
Console.ReadLine();
}
}
```
在这个示例中,我们首先创建了一个包含一千万个数字的数组。然后,我们使用十个线程来遍历数组,并在控制台上显示结果。我们将数组分成了十个块,每个线程处理一个块。线程使用 Lambda 表达式来执行任务,并使用 Start 方法启动线程。最后,我们使用 Join 方法等待所有线程完成任务,并在控制台上显示 "Done"。