c# 线程池:开启10个线程运行Fibonacci,并在所有线程运行完后,得出结果。
时间: 2023-07-04 14:19:06 浏览: 61
可以使用C#的线程池来实现这个需求。以下是示例代码:
```csharp
using System;
using System.Threading;
class Program
{
static int Fib(int n)
{
if (n <= 1)
return n;
return Fib(n - 1) + Fib(n - 2);
}
static void Main()
{
const int numThreads = 10;
const int n = 40;
int[] results = new int[numThreads];
// 开启线程池中的10个线程
AutoResetEvent[] doneEvents = new AutoResetEvent[numThreads];
for (int i = 0; i < numThreads; i++)
{
doneEvents[i] = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(state =>
{
int threadIndex = (int)state;
results[threadIndex] = Fib(n);
doneEvents[threadIndex].Set();
}, i);
}
// 等待所有线程运行完毕
WaitHandle.WaitAll(doneEvents);
// 打印结果
int sum = 0;
for (int i = 0; i < numThreads; i++)
{
Console.WriteLine("Thread {0}: Fib({1}) = {2}", i, n, results[i]);
sum += results[i];
}
Console.WriteLine("Sum of all results: {0}", sum);
}
}
```
上述代码中,我们使用了一个长度为10的数组来保存每个线程的计算结果,使用AutoResetEvent来等待所有线程运行完毕。在每个线程的回调函数中,我们根据线程的索引计算Fibonacci数列中的第n项,并将结果存储在对应的数组元素中。最后,我们使用WaitHandle.WaitAll方法等待所有线程完成,然后打印每个线程的结果以及所有结果的总和。