我正在尝试使用线程将数组的元素设置为等于其索引的平方根。我知道没有线程就可以轻松完成,但是我正在尝试学习线程。
运行此代码时,许多元素的默认值都不会更改为0。而且我不知道为什么。
class Program
{
static double[] array = new double[100000000];
static void Main()
{
int threadCount = 8;
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(() => SquareRoot(i, threadCount));
threads[i].Start();
}
for (int i = 0; i < threadCount; i++)
{
threads[i].Join();
}
}
static void SquareRoot(int start, int incrementSize)
{
for (int i = start; i < array.Length; i += incrementSize)
{
array[i] = Math.Sqrt(i);
}
}
}