我对多线程比较陌生。我编写了一个 for 循环,用于打印从 0 到用户指定的 int 数的值。我现在想以这样的方式并行化它,使每个线程打印 5 个数字。当我使用它时它正在工作Parallel.For()。但我似乎无法手动完成。这是代码。
using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static int no = 0;
static void Main(string[] args)
{
Console.WriteLine("Enter a number");
no = int.Parse(Console.ReadLine());
//Parallel.For(0, no, i =>
//Console.WriteLine(i)
//);
//Console.ReadLine();
int start = 0, end = 5, i = 0;
int not = no / 5;
if (no <= 5)
{
func(start, no);
}
else
{
int index = i;
Thread[] t = new Thread[not + 1];
while (index < not + 1)
{
if (end - start >= 5 && end <= no)
t[index] = new Thread(() => func(start, end));
else
t[index] = new Thread(() => func(start, no));
start = end;
end = end + 5;
i++;
t[index].Start();
}
Console.ReadLine();
}
}
static public void func(int start, int end)
{
for (int i = start; i < end; i++)
{
Console.Write(i+",");
}
}
}
}
假设用户输入值为 21。然后它产生以下输出
15,16,17,15,16,17,18,19,18,19,25,26,27,28,29,25,26,27,28,29
然而,在 t[index].start() 之后使用 thread.join() 后,会产生以下输出。
5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24
我似乎无法理解发生了什么,也无法调试此代码,因为有许多线程同时运行。
提前致谢